kotlinnestedinitialization

Using outer class's val/methods as defaults in nested data class declaration


Consider the following toy example:

class A{
    val a=1

    fun hello() =println("hello")

    init {
        println(a)
        println(this::hello)
    }

    data class B(val b: Int = a, val func: () -> Unit = this::hello)
}

This doesn't compile, linting the errors: Unresolved reference: a and 'this' is not defined in this context. This confuses me, since they are available inside the preceding init.

Why are the vals/vars/methods of the parent not accessible in the data class declaration, even though it's nested?

In spite of the plethora of SO questions matching "*kotlin*nested*data*", I couldn't find one answering this.


Solution

  • There are two different kinds of classes that can be declared inside another class:

    Read more in the documentation about Nested and inner classes.

    As a closing note, since you talked about parent class in your question: Parent classes only exist in inheritance hierarchies where one class extends another. That is entirely unrelated though and has nothing to do with the code from your example. Your code is about an outer and an inner/nested class, not about parent and child classes.