Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - nullable property default to null value

Suppose I define a class with a nullable property

class ABC {
   var myProperty: String? = null
}

Is there a way to default it to null value? Maybe something similar to SCALA?

var myProperty: String? = _  // compilation error

or simply:

var myProperty: String?  // compilation error

I know we could have used a lateinit variable that from Kotlin 1.2 can be later checked for initilization like so:

lateinit var myProperty: String

if (::myProperty.isInitialized) {
   //value is not-null
}

So is lateinit the preferred way? Is defaulting to null value possible or it's omitted on purpose?

like image 392
kosiara - Bartosz Kosarzycki Avatar asked Aug 01 '18 07:08

kosiara - Bartosz Kosarzycki


People also ask

How do I assign a value to null in Kotlin?

In an effort to rid the world of NullPointerException , variable types in Kotlin don't allow the assignment of null . If you need a variable that can be null, declare it nullable by adding ? at the end of its type. Declares a non- null String variable.

How do you handle nullable in Kotlin?

Kotlin has a safe call operator (?.) to handle null references. This operator executes any action only when the reference has a non-null value. Otherwise, it returns a null value. The safe call operator combines a null check along with a method call in a single expression.

What is the correct way to initialize a nullable variable in Kotlin?

Therefore you have to do the initialization var x : String? = null . Not assigning a value is only the declaration of the property and thus you'd have to make it abstract abstract val x : String? . Alternatively you can use lateinit , also on non-nullable types.

Why is Kotlin null safe?

Null Comparisons are simple but number of nested if-else expression could be burdensome. So, Kotlin has a Safe call operator, ?. that reduces this complexity and execute an action only when the specific reference holds a non-null value.. It allows us to combine a null-check and a method call in a single expression.


1 Answers

Kotlin intentionally requires you to initialize all properties explicitly. There is no shorthand syntax. For a property of a nullable type, the preferred way is not to use lateinit, but to declare it with a null initializer.

The isInitialized method for lateinit properties is designed to handle complex cases like cleanup of resources; it's not intended to be used as a replacement for a null check for users who want to save on writing = null as part of a property declaration.

like image 78
yole Avatar answered Oct 13 '22 22:10

yole