Wednesday 10 January 2018

Kotlin: Inner classes

Inner classes are like nested class, only difference is you can access the members of outer class from inner class.

How to define inner class?
Inner class is defined using the keyword ‘inner’.

How to define object of inner class?
var innerObj = Outer().Inner()

InnerDemo.kt
class Outer {

 fun printMsg() {
  println("Inside Outer class")
 }

 inner class Inner {
  fun printMsg() {
   println("Inside Inner class")
  }
 }
}

fun main(args: Array<String>) {
 var outerObj = Outer()
 var innerObj = Outer().Inner()

 outerObj.printMsg()
 innerObj.printMsg()
}

Output
Inside Outer class
Inside Inner class

You can able to access the member variables of outer class from inner class.


InnerDemo.kt

class Outer {
 private var x = 10

 inner class Inner {
  fun getX() = x
 }
}

fun main(args: Array<String>) {
 var innerObj = Outer().Inner()

 var x = innerObj.getX()

 println("x = $x")
}

Output

x = 10


Previous                                                 Next                                                 Home

No comments:

Post a Comment