Nullable types - patterns for getting rid of them?

I would note that for state machines, you probably do want nullable types, as the type system is preventing you from getting confused and trying to access state that might not actually be there yet. The lateinit modifier is intended for the case where a reflection based framework is injecting stuff into your classes fields right at the start, or where something is being initialised in a method called from the c’tor but not actually in the c’tor.

Kotlin internally has the same thing as Swift: a reference that came from Java is written as Foo! and null safety is disabled for that reference. However you cannot write this yourself in the language: if you write a type, you always have to pick.

There are a variety of useful patterns to help you get rid of the !!s. One is to realise that if you assign the result to a local on-stack val, you don’t need to do it again each time. Another is to use ?.let { … } where the value “it” will be non-null inside the block.

1 Like