Inner classes

A class that is declared with the inner keyword is called an inner class in Kotlin. Let's extend the previous example by creating an Outer class with one additional property, called counter. Add the inner keyword with the Nested class and create an incrementCounter() that increases the counter value. Remember that the counter is not a Nested class property but instead an Outer class member. The Nested class is declared as an inner class so the members of the Outer class are directly accessible:

class Outer {
val out = "Outer class"
var counter = 0
fun info() {
println("I am an outer class function")
}

inner class Nested {
val nest = "Nested class"
fun info() {
println("I am a nested class function")
}
fun incrementCounter(){
counter++
}
}
}

Let's create instances of both classes and verify whether the nested class increases the value of the counter variable from the outer class by calling incrementFunction() from the inner class:

fun main(args: Array<String>) {

val outerObj = Outer()
val nestedObj = outerObj.Nested()

println("Outer class counter before increment = "+ outerObj.counter)
nestedObj.incrementCounter()
println("Outer class counter after increment = "+ outerObj.counter)
}

Create instances of the Outer and Nested classes, and display the the output of  counter by using outerObj. Call the incrementCounter() function by using nestedObj and verify the value of the counter property:

Outer class counter before increment  = 0
Outer class counter after increment = 1

As we can see, the value of the outer variable is increased by the incrementCounter() function of the inner class. There is one more interesting point to discuss. Declare a new counter property inside the inner class and execute the program again. This time, incrementCounter() will increase the counter from the Nested class instead of the Outer class, so we can access the Outer class member only if the inner class contains a member with the same signature:

class Outer {

val out = "Outer class"
var counter = 0
::::::::
inner class Nested {
val nest = "Nested class"
var counter = 0
:::::::::
fun incrementCounter(){
[email protected]++
}
}
}

Use the this@ keyword to access the Outer class and its member. Add the following line to the incrementCounter() function and execute the program. You will see the same output as before:

class Outer {

val out = "Outer class"
var counter = 0

fun info() {
println("I am an outer class function")
}

inner class Nested {

val nest = "Nested class"
var counter = 0

fun info() {
// [email protected]()
println("I am a nested class function")
}

fun incrementCounter(){
this@Outer.counter++
}
}
}

[email protected]++  will access the counter property of the Outer class and increment in it.

..................Content has been hidden....................

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