Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kotlin, is it ok to call null.also{}

There is code like:

result.also{......}

but the result might be null and the compiler does not complain, it is same as

null.also{...}

is it ok to call also{} on null?

like image 797
lannyf Avatar asked Aug 21 '18 12:08

lannyf


People also ask

Which is not allowed on a nullable receiver Kotlin?

In Kotlin, you cannot access a nullable value without being sure it is not null (Checking for null in conditions), or asserting that it is surely not null using the !!

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

Should I use null in Kotlin?

Valid usages of null in KotlinIf you need a way to represent whether a value is initialized or whether it has no value, then null is appropriate in this case.

What is correct about null safety in Kotlin?

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

Yes it is. As the function definition tells you...

inline fun <T> T.also(block: (T) -> Unit): T (source)

...T does not define any upper bound and may therefore be used with any, nullable and non-nullable, type (<T> is the same as <T: Any?>).

If you're afraid about NullPointerExceptions, you don't need to be. The also function simply invokes the block with its receiver, null in your case, before again returning the receiver. For example, the following is legit:

 //returns null and _also_ prints "null"
return null.also { println(it) }
like image 61
s1m0nw1 Avatar answered Sep 29 '22 00:09

s1m0nw1