Tuesday 9 January 2018

Kotlin: Nested classes

A class can be nested in other class.

Ex
class Outer {

         class Nested {

         }
}

How to create an object to nested class?
var obj = Outer.Nested()

NestedClass.kt
class Outer {

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

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

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

 outerObj.printMsg()
 nestedObj.printMsg()
}

Output
Inside Outer class
Inside Nested class

Can I access the member variables defined in outer class from nested class?
No, you can’t access the member variables defined in outer class from nested class.


NestedDemo.kt

class Outer {
 private var x = 10

 class Inner {
  fun getX() = x
 }
}

When you try to compile above program, you will end up in below error.

Unresolved reference: x


Previous                                                 Next                                                 Home

No comments:

Post a Comment