English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this article, you will learn how to use nested and inner classes with examples.
Similar to Java, Kotlin allows you to define a class within another class called a nested class
class Outer { ... .. ... class Nested { ... .. ... } }
Since the nested class is an external (Outer) member of the enclosing class, you can use the . symbol to access the nested class and its members.
class Outer { val a = "Outside the nested class." class Nested { val b = "Within the nested class." fun callMe() = "Function call from within the nested class." } } fun main(args: Array<String>) { //Access the members of the nested class println(Outer.Nested().b) //Create an object of the nested class val nested = Outer.Nested() println(nested.callMe()) }
When running the program, the output is:
Within the nested class. Function calls from within the nested class.
For Java users
Nested classes in Kotlin are similar to static nested classes in Java.
In Java, when you declare a class within another class, it becomes an inner class by default. However, in Kotlin, you need to use the inner modifier to create an inner class, which we will discuss below.
Nested classes in Kotlin do not have access to the outer class instance. For example,
class Outer { val foo = "Outside the nested class." class Nested { //Error! Cannot access the members of the outer class. fun callMe() = foo } } fun main(args: Array<String>) { val outer = Outer() println(outer.Nested().callMe()) }
The above code cannot be compiled because we are trying to access the foo property of the outer class from within the nested class.
To solve this problem, you need to use the inner keyword to mark the nested class to create an inner class. An inner class carries a reference to the outer class and can access the members of the outer class.
class Outer { val a = "Outside the nested class." inner class Inner { fun callMe() = a } } fun main(args: Array<String>) { val outer = Outer() println("Use outer objects: ${outer.Inner().callMe()}") val inner = Outer().Inner() println("Use inner objects: ${inner.callMe()}") }
When running the program, the output is:
Use outer objects: Outside the nested class. Use inner objects: Outside the nested class.