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
?
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 !!
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.
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.
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.
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) }
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