Kotlin : How to use if-else like condition with let block for 'null' checks
Source - kotlinlang.org
- ?. performs a safe call (calls a method or accesses a property if the receiver is non-null)
- ?: takes the right-hand value if the left-hand value is null (the elvis operator)
Change ?. with ?: will solve this issue,
Code base as following, will run either let or run block based upon the null check.
var someValue : String? = null
someValue = "SOF"
someValue?.let {safeSomeValue->
//This code block will run only if someValue is not null
}?:run {
//This code block will run only when if someValue is null, like else condition
}
I am replacing all the null check with let block in my code
The first question here is, why? Is this somehow more readable for you than the regular if-else
structure? I'd be generally wary of refactoring just for refactoring's sake.
The second consideration is much more important: this conversion you're doing is not equivalent to the original code, you're actually modifying the behavior with this change. Take the following piece of code:
var someValue : String? = null
someValue = "SOF"
someValue?.let {safeSomeValue->
foo(someSafeValue)
bar(someSafeValue)
} ?: run {
println("shouldn't happen if someValue != null")
}
You expect the run
block to execute only if someValue == null
, but that's actually not the only case when it will run. The entire someValue?.let { ... }
expression can produce null
values not just when someValue
itself was null
, but also if the block passed to let
returned null
. In this case, if the bar()
function call results in null
, the run
statement will be executed afterwards, therefore running both branches of what you thought was a fancied up if-else
statement.