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

I was developing an abstract & generic base class where the generic parameter defines the type of an abstract field. This field would be initialized by inherited classes, so I applied the 'lateinit' modifier to it which caused 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

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