Not nullable list with null initialized - is that intended?

While using of kotlin=1.5.31 I get a runtime null pointer when I init a not nullable list. I would expect an initialization/construction error.

class Cycle() {
    val notNullableList: List<Any>

    init {
      notNullableList = nullPointer()
    }

    private fun nullPointer(): List<Any> = notNullableList
  }

  @Test
  fun test() {
    // null pointer after initialization
    assertNotNull(Cycle().notNullableList)
  }

Is that runtime null pointer intended?
Cannot the compiler detect NP cycles like that?

Yes, this is expected and described in the documentation: Null safety | Kotlin Documentation

The only possible causes of an NPE in Kotlin are: (…) Data inconsistency with regard to initialization, such as when: (…) An uninitialized this available in a constructor is passed and used somewhere (a “leaking this”).

It would be pretty hard to detect and disallow such cases at compile time, but at the same time allow some flexibility in initialization.

1 Like

Tanks @broot for the quick answer.