Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ?.let returns nullable even if it evaluates to a non-null

Tags:

kotlin

Kotlin's standard function let is defined like this:

public inline fun <T, R> T.let(block: (T) -> R): R

Doesn't this mean the return type of let will be whatever the block returns?

Why doesn't this work?

var a: String? = "maybe null" 
val x: Boolean = a?.let { 
    a.contains("maybe") // note that contains returns Boolean, not Boolean?
}

This complains: Type missmatch: Required Boolean, Found Boolean? Shouldn't it return a Boolean since contains function returns a Boolean ?

I'm sure I've misunderstood something. Maybe someone can help me and other newbies to understand better.

like image 231
osrl Avatar asked Sep 17 '18 13:09

osrl


1 Answers

a?.let returns whatever you do inside the given let-block, BUT as a might be null you are not sure whether the let-block is even called. That's why x must be either Boolean? or you need to specify what should be returned if a is null, e.g.:

val x: Boolean = a?.let { a.contains("maybe") }
                  ?: false // this is used if `a` is null
like image 146
Roland Avatar answered Oct 16 '22 12:10

Roland