使用Kotlin的“let”的合理情况

在Kotlin中,如果一个对象( let接收者)不为null ,那么通常使用let来执行代码,以替代if != null检查,如下所示:

 val nullable: String? = "anything" nullable?.let { println(it) } 

在其他情况下,利用let是否有意义?

仅供参考, let Kotlin的stdlib,定义如下:

 @kotlin.internal.InlineOnly public inline fun <T, R> T.let(block: (T) -> R): R = block(this) 

我见过let用来限制嵌套变量(忽略let返回):

  some.nested.foo.bar.let { bar -> doSomething(bar) doMoreStuff(bar) } 

它可以很好,因为它取代了定义一个局部变量的需求,但我不确定它实际上是多么有用。

也可以用apply来完成,尽管可读性稍差,(而不是范围中的bar )。

当您使用可为空的var变量时, let也很有用。 例如,我们有这个代码

 fun doSomething(value: String) { } class A { var boo: String? = null fun b() { if (boo != null) { doSomething(boo) } } } 

在那里, if块内部有编译时错误,因为boo可以在外面改变。 为了解决这个问题,我们应该创建一个val变量

 class A { var boo: String? = null fun b() { val b = boo if (b != null) { doSomething(b) } } } 

或者使用let

 class A { var boo: String? = null fun b() { boo?.let { doSomething(it) } } }