Home > Software engineering >  List find method finds nothing, but let is called (?!)
List find method finds nothing, but let is called (?!)

Time:07-12

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 ?

CodePudding user response:

null is still a value so it makes sense that the first block is run. it'd be the same as if you ran null.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.

CodePudding user response:

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 on null it throws NullPointerException

You have to use Kotlins safe call operator ?., which call method when insatce is not null and when is it returns null.

?: operator is called Elvis operator and it returns first value if it is not null, else it returns second value.

So just change in your code dot operator . to safe call operator ?.:

myList.find { it.code == item.bin }.let {
               // 1

            } ?: run {
               // 2
                
            }
  • Related