tutorial, no_image, kotlin,

Kotlin - no_image

Upendra Upendra Follow Jan 23, 2025 · 2 mins read
Kotlin - no_image
Share this

nested class vs inner class

A nested class is the class that is declared inside another class, for example:

class Outer {
    private val bar: Int = 1
    class Nested {
        fun foo() = 2
    }
}

val demo = Outer.Nested().foo() // == 2

Nested classes cannot directly access members (including private members) of the outer class.1 To create the nested class you don’t require an instance of the outher class.

An inner class is a nested class but declared by the adding the keyword inner:

class Outer {
    private val bar: Int = 1
    inner class Inner {
        fun foo() = bar
    }
}

val demo = Outer().Inner().foo() // == 1

Inner classes have access to all members (including private members) of the outer class. This creates a strong association between the two classes.2 To create the inner nested class you require an instance of the outher class.

Differences Between Nested and Inner Classes

| Feature | Nested Class | Inner Class | |—|—|—| | Access to Outer Class | No | Yes | | Keyword Used | No specific keyword | inner keyword | | Use Cases | Utility classes, logical grouping | Callbacks, tightly coupled logic | | Instantiation | OuterClass.NestedClass() | outerInstance.InnerClass() |

Comparison with Java

Kotlin classes are much similar to Java classes when we think about the capabilities and use cases, but not identical. Nested in Kotlin is similar to a static nested class in Java and the inner class is similar to a non-static nested class in Java.

Kotlin Java
Nested class Static Nested class
Inner class Non-static nested class

Best Practices

  • Use Nested Classes for Independence. If the inner class does not need to interact with the outer class, prefer using a nested class;
  • Use Inner Classes for Encapsulation. When you need the inner class to work closely with the outer class, encapsulating logic, use an inner class;
  • Keep it Simple. Avoid overusing nested or inner classes, as they can make the code harder to read if not used judiciously.

Links

Nested and inner classes

Understanding Nested and Inner Classes in Kotlin

Understanding Inner Classes and Nested Classes in Kotlin

Further reading

What is the purpose of inner class in kotlin?

Nested & Inner classes in Kotlin

Nested and Inner Class in Kotlin

Nested and inner classes

credit goes to @swayangjit
Join Newsletter
Get the latest news right in your inbox. We never spam!
Upendra
Written by Upendra Follow
Hi, I am Upendra, the author in Human and machine languages,I don't know to how 3 liner bio works so just Connect with me on social sites you will get to know me better.