Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why late init var cannot be used with Nullable?

Why can't we use lateinit with nullable variables?

lateinit var v: String?

lateinit modifier is not allowed on properties of nullable types

like image 371
Abraham Mathew Avatar asked May 29 '19 05:05

Abraham Mathew


People also ask

Can Lateinit be nullable?

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.

When should I use Lateinit?

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.

Can we use Lateinit with Val?

You cannot use val for lateinit variable as it will be initialized later on.

Why do we need Lateinit?

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.


1 Answers

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

like image 157
Gunaseelan Avatar answered Sep 21 '22 23:09

Gunaseelan