tl;dr: https://youtrack.jetbrains.com/issue/KT-22044 is a good fit regarding this issue.
I will cite what Intellij IDEAs inspection called “Leaking ‘this’ in constructor” says about this:
This inspection reports dangerous operations inside constructors including:
- Accessing a non-final property in constructor
- Calling a non-final function in constructor
- Using this as a function argument in a constructor of a non-final class
These operations are dangerous because your class can be inherited, and a derived class is not yet initialized at this moment. Typical example:
abstract class Base { val code = calculate() abstract fun calculate(): Int } class Derived(private val x: Int) : Base() { override fun calculate() = x } fun testIt() { println(Derived(42).code) // Expected: 42, actual: 0 }
I think that there should be warning nonetheless as you were able to access a non-initialized variable. The reason: the compiler already disallows direct access to uninitialized variables, i.e. the following will not compile:
class Demo {
val some : Int
init {
println(some) // Variable 'some' must be initialized
but accessing it indirectly compiles and shows the default value of the variable type:
class Demo2 {
val some : Int
val someString : String
init {
fun Demo2.indirectSome() = some
fun Demo2.indirectSomeString() = someString
println(indirectSome()) // prints 0
println(indirectSomeString()) // prints null; and yes.. this can lead to NullPointerExceptions
and there we also have a “leak”, basically accessing some
before it should 😉