kotlin constructor properties function nested class inner class
Classes can contain:
- Constructors
- Constructor initializer blocks
- Functions
- Properties
- Nested and Inner Classes (That we will talk about here)
- Object Declarations
Nested and inner classes
Nested class
Classes can be nested in other classes. Note that a nested class can’t access a parameter in the outer class:
class Outer {
private val x = 1 class Nested {
//fun foo() = 2 * x //this won’t compile fun foo() = 2
}
}
That gives in repl:
val foo = Outer.Nested().foo()
foo
2
Inner class
Mark a class as inner if you need to access members of the outer class:
class Outer {
private val x = 1 inner class Inner {
fun foo() = x * 2
}
}
Gives in repl:
val foo = Outer().Inner().foo()
foo 2
You can see the difference between the syntax when you use a nested class versus when you use an inner class:
val foo = Outer.Nested().foo() val foo = Outer().Inner().foo()
If you try to create an inner class without first creating an instance of the outer class you’ll see this error:
val foo = Outer.Inner().foo()
error: constructor of inner class Inner can be called only with receiver of containing class
val foo = Outer.Inner().foo()