Skip to content
Tutorials Center
My learning

Topics

Lesson 54 of 134 ยท Classes and Objects

Nested and Inner Classes

Learn the difference between Kotlin nested and inner classes, this@Outer, local classes and anonymous objects, plus memory-leak pitfalls and when to nest, with runnable code.

You can declare a class inside another class. Kotlin offers this in several flavors, and the difference between them is one keyword and one hidden reference. A nested class is just a class that lives in the namespace of another; it knows nothing about the outer object. An inner class, marked inner, is tied to one specific instance of the outer class and can reach its members. A local class is declared inside a function, and an anonymous object has no name at all.

The most common beginner mistake is to expect Java's behavior. In Java, a class inside a class is an inner class by default; in Kotlin it is a nested one, and inner is opt-in. This lesson explains the four forms, shows the compile error you hit when you mix them up, and covers the memory pitfalls of inner classes. It builds on Classes and Properties and Objects and Companion Objects.

Nested classes: grouping, nothing more

A class declared inside another class, without inner, is a nested class. It is used through the outer name (Outer.Nested) and has no access to the outer instance:

Kotlin A nested class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Pizza.Topping can be created without any Pizza around, as the last lines show. Nesting here communicates "a topping only makes sense in the context of pizzas" and keeps the name from polluting the package namespace. Nested classes can be private, which hides helper types completely:

Kotlin A private nested helper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Entry is an implementation detail: nobody outside Playlist can see or name it. This is the best reason to nest, and it is also why Kotlin made it the default. Nested classes can also be objects, interfaces, enums and sealed types, which is how sealed hierarchies are often organized (see Sealed Classes and Interfaces).

The compile error: reaching the outer instance

Because a nested class has no outer instance, trying to use the outer class's members is an error:

Kotlin A nested class cannot see the outer instance (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler answers with error: outer class 'class Outer : Any' of non-inner class cannot be used as receiver. Which Outer would it even read? Outer.Nested() was created with no Outer at all. If you do want a link to an outer object, you have two choices: pass it in explicitly as a constructor parameter, or make the class inner.

Inner classes: tied to an outer instance

An inner class carries a hidden reference to the object that created it. It can read and change the outer members, and it is created from an outer instance:

Kotlin An inner class and this@Outer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Each Account belongs to one Bank: ana updates North's total and bo updates South's. Inner objects are created with outer.Inner(...), or just Inner(...) from inside the outer class. When an inner member has the same name as an outer member, qualify the outer one with the label this@Outer; plain this is the inner object. [email protected] above picks the bank's name even though Account has no name property of its own.

Name clashes show why the label exists:

Kotlin this, this@Inner and this@Outer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Lambdas with receivers use the same labels; see Scope Functions for the related this@label forms.

The cost of inner: a hidden reference

Because an inner object keeps its outer object alive, an inner class costs one extra field per instance, and, more importantly, it can cause memory leaks. If the inner object lives longer than the outer one (stored in a cache, passed to a long-running task, registered as a listener), the outer object, and everything it references, cannot be garbage collected.

This is the classic Android bug of holding an Activity through an inner class. The same logic applies anywhere, so ask: "does this class really need the outer instance?" If it only needs one or two values, make it nested and pass them in:

Kotlin Nested with explicit parameters instead of inner

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Rules of thumb: default to nested; use inner only when the class genuinely represents "a part of one particular outer object" (an iterator over a collection, an account of a bank, a view of a model).

Local classes

A class can be declared inside a function body. It is visible only there, and it can use the function's local variables and parameters (capturing them, like a lambda):

Kotlin A local class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Tick is reachable only inside countdown and reads the parameter label. A local class is handy for a one-off helper in a long function, but if you need it in two places, promote it. Local classes cannot have a visibility modifier; the function is their scope. As with a local function (Local and Nested Functions), prefer a private nested class once the function grows large.

Anonymous objects

An anonymous object (an object expression) implements an interface or extends a class right where it is needed, without naming a type. You met it in Objects and Companion Objects; here it is as an inner-class replacement for callbacks:

Kotlin An anonymous object with state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The object has its own field (calls) and also captures outer variables (seen, evens) and can change them. For a single-method interface declared as fun interface, a lambda is shorter; for anything with several members or its own state, use an anonymous object.

Choosing between them

Form Needs outer instance? Reaches outer members? Typical use
nested class No No Grouping, private helper types, sealed cases
inner class Yes Yes (this@Outer) A part of one outer object
local class Function scope Locals and parameters One-off helper inside a function
anonymous object n/a Captured variables Callbacks, one-off implementations

If you are unsure, write a nested class and see whether the compiler asks for the outer instance. Adding inner when it complains is a conscious step, and that is the point of Kotlin's default.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the default for a class declared inside another class in Kotlin?

    Unlike Java, Kotlin nested classes are static-like by default. You must write inner to get an outer instance reference.
  2. 2. How do you create an instance of inner class Account declared in class Bank, given val b = Bank()?

    An inner class is created from an outer instance, written outer.Inner(...), because the new object keeps a reference to that outer object.
  3. 3. Inside an inner class, which expression refers to the outer class instance?

    this@Outer is the labeled this. Plain this is the inner object.
  4. 4. Why can inner classes cause memory leaks?

    The hidden outer reference keeps the whole outer object, and everything it holds, alive for as long as the inner object is referenced.
  5. 5. What error do you get when a nested (non-inner) class uses a private property of the outer class?

    A nested class has no outer instance, so the compiler rejects the access. Adding inner (or passing the value in) fixes it.

Summary

  • A class declared inside another is nested by default: it is only grouped by name and has no access to an outer instance.
  • Add inner to link a class to one outer object; create it with outer.Inner() and reach the outer with this@Outer.
  • Inner objects keep their outer object alive: prefer nested classes and pass what you need, to avoid leaks.
  • Local classes live inside a function and capture its variables; anonymous objects implement an interface or class in place, with their own state.
  • Private nested classes are the cleanest way to hide implementation details.

Next: Value Classes