Why can't we use lateinit
with nullable variables?
lateinit var v: String?
lateinit
modifier is not allowed on properties of nullable types
For this reason, we can't use lateinit variables with nullable types, either. Even if it was possible to implement lateinit primitive variables with nullable types, it doesn't make sense to do so. As we know, we're using lateinit variables to avoid the awkwardness of nullable types.
lateinit means that variable must be initialised later. It should be initialized before accessing it. If you attempt accessing uninitialized lateinit variable UninitializedPropertyAccessException will be thrown. It's always better to avoid using nulls in your app.
You cannot use val for lateinit variable as it will be initialized later on.
The lateinit keyword allows you to avoid initializing a property when an object is constructed. If your property is referenced before being initialized, Kotlin throws an UninitializedPropertyAccessException , so be sure to initialize your property as soon as possible.
lateinit
is only for avoid null checks in future, that's why lateinit
modifier is not allowed on properties of nullable types.
If you want it to be nullable
then simply you can use like var b: String? = null
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With