Kotlin Inner vs Nested Classes: How the inner Keyword Changes Memory and Access

In Kotlin, a nested class is declared inside another class but holds no reference to any outer object, so it behaves like a namespace member. Marking a class as inner ties each instance to a specific outer object, letting it access that object's members, including private ones. This link comes at a cost, because the inner instance keeps the outer object alive as long as it exists, which can cause memory leaks such as in Android Activities. Inspecting the decompiled bytecode shows that inner classes gain a hidden reference field and an extra constructor parameter, while nested classes are compiled as static. The article advises developers to use inner only when they truly need access to the outer instance, rather than adding it to silence a compiler error.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in