‘lateinit’ modifier is not allowed on properties of a type with nullable

While developing an abstract & generic base class where the generic parameter defines the type of an abstract field. The field would be initialized by the inherited classes, and so I applied the 'lateinit' modifier to it. This cause an interesting error:'lateinit' modifier is not allowed on properties of a type with nullable 

The class itself looked a little like this:

abstract class Block<State>() {
    ...
    protected lateinit var state: State
    ...
}

So it turns out, when you don’t apply any bounds to a generic parameter, it defaults to Any?. Therefore the compiler was really seeing this:

abstract class Block<State: Any?>() {
    ...
    protected lateinit var state: State
    ...
}

If you know the rules for lateinit, you’ll remember that it cannot be used with optional values, and so I was getting the error. The solution was to apply a non-optional bounds to the State parameter, like this:

abstract class Block<State: Any>() {
    ...
    protected lateinit var state: State
    ...
}

Everything worked great after this small change.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.