i have the following code:
myList.find { it.code == item.bin }.let {
// 1
} ?: run {
// 2
}
I would expect that, if item is found, I enter block 1 , otherwise block 2 ;
But instead I enter block 1 in all cases, and if nothing is found , it is null
Android studio seems aware of this, as the block 2 is grey (it is code never called), but I can’t figure why
Please may someone explain why ?
2
Answers
null
is still a value so it makes sense that the first block is run. it’d be the same as if you rannull.let { println("hey!") }
.you probably want to run
let
with a null check:myList.find { it.code == item.bin }?.let { ... }
. this way the block will only run if there is indeed a value being returned that is not null.You are using classic dot call operator
.
, this operator is not allowed on nullable types. If you want to call this operator on nullable type insert!!
before operator, but if you call it onnull
it throws NullPointerExceptionYou have to use Kotlins safe call operator
?.
, which call method when insatce is notnull
and when is it returnsnull
.?:
operator is called Elvis operator and it returns first value if it is notnull
, else it returns second value.So just change in your code dot operator
.
to safe call operator?.
: