Kotlin - Nested Class Example

A nested class is a class which is created inside another class. In Kotlin, the nested class is by default static, so its data member and member function can be accessed without creating an object of a class. The nested class cannot be able to access the data member of the outer class.

Kotlin Nested Class Example

package net.javaguides.kotlin

class outerClass {
    var name: String = "outerClass"

    class nestedClass {
        var description: String = "code inside nested class"
        var id: Int = 101
        fun foo() {
            //  print("name is ${name}") // cannot access the outer class member  
            println("Id is ${id}")

fun main(args: Array < String > ) {
    // nested class must be initialize  
    println(outerClass.nestedClass().description) // accessing property  
    var obj = outerClass.nestedClass() // object creation  
    obj.foo() // access member function  
code inside nested class
Id is 101

Free Spring Boot Tutorial - 5 Hours Full Course

Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course