Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Set to Null If Not Null

Tags:

null

kotlin

Is there an idiom in Kotlin for setting a variable to null if it is not already null? Something more semantically pleasing than:

var test: String? = null
if(test != null) test = null
like image 678
Eliezer Avatar asked Sep 20 '16 00:09

Eliezer


People also ask

How do you set 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.

IS NOT null in Kotlin?

Nullable and Non-Nullable Types in Kotlin – Kotlin type system has distinguish two types of references that can hold null (nullable references) and those that can not (non-null references). A variable of type String can not hold null. If we try to assign null to the variable, it gives compiler error.

How do I check if an object is null in Kotlin?

You can use the "?. let" operator in Kotlin to check if the value of a variable is NULL. It can only be used when we are sure that we are refereeing to a non-NULL able value.

Can any be null Kotlin?

Consequently, any variable cannot contain the null value unless you explicitly say it can. This way, you can avoid the danger of null references, and you do not have to wait for exceptions or errors to be thrown at runtime. Kotlin supports this possibility since its first release, and it is called null safety.


3 Answers

You can use the execute if not null idiom:

test?.let { test = null }
like image 149
mfulton26 Avatar answered Dec 17 '22 00:12

mfulton26


Just assign null to local variable:

test = null

In case if it's not null - you assign null to this variable. In case if variable is null - you just assign null to it, so nothing changed.

like image 37
Ruslan Avatar answered Dec 17 '22 00:12

Ruslan


I came up with this extensions which makes this simpler:

inline fun <T, R> T.letThenNull(block: (T) -> R): T? { block(this); return null }
val test: Any? = null
...
test = test?.letThenNull { /* do something with test */ }
like image 22
Eliezer Avatar answered Dec 17 '22 01:12

Eliezer