You actually have to initialize the variable on the time of object creation in the variable declairation itself or in the init{}
block, since there is no preinit null type in the Kotlin.
And since your variable is val
not var
you cannot set it after created so there's no point of creating the variable.
If you meant to initialize the variable later on but only once, check this answer: https://stackoverflow.com/a/48445081/11377112
This is done by delegation like this:
class InitOnceProperty<T> : ReadWriteProperty<Any, T> {
private object EMPTY
private var value: Any? = EMPTY
override fun getValue(thisRef: Any, property: KProperty<*>): T {
if (value == EMPTY) {
throw IllegalStateException("Value isn't initialized")
} else {
return value as T
}
}
override fun setValue(thisRef: Any, property: KProperty<*>, value: T) {
if (this.value != EMPTY) {
throw IllegalStateException("Value is initialized")
}
this.value = value
}
}
Now you can delegate the variable by the delegate
var property: Int by InitOnceProperty()