Today I encountered this crash: ```fun main() { ...
# random
s
Today I encountered this crash:
Copy code
fun main() {
    Foo()
}

class Foo {
    val bar = Bar() // fails because outerBaz is not yet initialized
    val outerBaz = "Baz"
    
    inner class Bar(
        val innerBaz: String = outerBaz
    )
}
Copy code
Exception in thread "main" java.lang.NullPointerException: Parameter specified as non-null is null: method Foo$Bar.<init>, parameter innerBaz
 at Foo$Bar.<init> (File.kt:-1) 
 at Foo$Bar.<init> (File.kt:9) 
 at Foo.<init> (File.kt:6)
(https://pl.kotl.in/OetJ4wyvS) I would think/hope this was something that could be caught at compile-time. Is this is a known issue? My YouTrack-fu is failing me.
For completion's sake, this rightfully causes a compile-time error:
Copy code
fun main() {
    Foo()
}

class Foo {
    val bar = outerBar // compile-time error here
    val outerBaz = "Baz"
}
Copy code
Compilation failed:
Unresolved reference 'outerBar'.
(https://pl.kotl.in/9Io-rZ1RG)
s
Yes, it's a known issue, there's a whole category of YouTrack tickets for problems in this area. You can find them linked to this parent ticket: https://youtrack.jetbrains.com/issue/KTIJ-9751
I don't know if there's a ticket specifically for inner classes like the one in your example, but it all relates back to the same basic problem
The inner class has an implicit reference to the outer object, but when the inner class constructor is executed, the outer object isn't yet fully initialized. Initialization is when properties get their values; before that, they're all null/zero, even if they have non-nullable types :(
s
Ahh, nice, thanks for pointing me to that parent issue! Definitely something to keep in mind, and nothing I encounter very often, but I've gotten so used to the compiler saving me from these kinds of issues. 😅
👍 1