简体   繁体   中英

Kotlin 'let' usage

Is there a difference between this piece of code:

fun isDogEating(): Boolean {
    return dog?.let { return it.eating } ?: false
}

and this

fun isDogEating(): Boolean {
    return dog?.eating ?: false
}

I bumped into something like the first and was wondering whether the let is redundant here.

There are no differences in behavior.

Both functions return false if dog == null , because of the ?: false at the end.

The let function is only executed if dog != null . Same with the eating property in the second example

Note that the return statement in the let lambda means to return from the isDogEating function, not from the lambda! To return from the lambda one may use the return@let or just the expression

I prefer a shorter version:

fun isDogEating() = dog?.eating ?: false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM