Nested classes

Kotlin allows classes to be declared inside the body of another class. Other modern OO languages also allow this, and these kinds of classes are usually called nested or inner classes. Here's an example of how you would declare a nested class:

class User(val name: String) {
class Address(val street: String,
val streetNumber: String,
val zip: String,
val city: String)
}

And if you'd like to instantiate the Address class, you would have to do it like this, prefixing the containing class first:

val address = User.Address("Aparo Park", "1", "ABC", "Gotham City")

Visibility modifiers can be applied to nested classes as well. Here's the same example, but this time the nested class is private:

class User(val name: String) {
private class Address(val street: String,
val streetNumber: String,
val zip: String,
val city: String)


private val address = Address("Aparo Park", "1", "ABC", "Gotham City")
}

Now the Address class cannot be instantiated like in the previous example, because it is visible only inside the User class. Also, the property address has to be private, otherwise it would expose the private class to the outside and the compiler will not allow this.

Java also supports nested classes, and in Java they can access the containing class and its members by default (nested classes have an implicit reference to the outer containing class). Java also allows nested classes to have a static modifier. In that case, they don't have an implicit reference to the outer containing class.

Kotlin's nested classes have the opposite as the default. They don't hold an implicit reference to the outer class. If you want to enable this, you have to add the inner keyword to your nested class. The following example illustrates this:

class User(val name: String) {
class Address(val street: String,
val streetNumber: String,
val zip: String,
val city: String) {
init {
// compiler error, can't access name property
println("The name of the User is: $name")
}
}
}

If you add the inner keyword, you can access members from the outer class:

class User(val name: String) {

inner class Address(val street: String,
val streetNumber: String,
val zip: String,
val city: String) {

init {
//we can access the name property from the outer class
println("The name of the User is: $name")
}
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.87.235