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.
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
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