kotlin - 了解 Kotlin 的必要性

标签 kotlin let

我试图理解为什么需要 let。在下面的示例中,我有一个带有函数 giveMeFive 的类 Test:

public class Test() {
    fun giveMeFive(): Int {
        return 5
    }
}

给定以下代码:

var test: Test? = Test()

var x: Int? = test?.giveMeFive()

test = null

x = test?.giveMeFive()
x = test?.let {it.giveMeFive()}

x 设置为 5,然后在 test 设置为 null 后,调用以下任一语句为 x 返回 null。鉴于在空引用上调用方法会跳过调用并将 x 设置为空,为什么我还需要使用 let?在某些情况下只是?行不通,需要 let 吗?

此外,如果被调用的函数没有返回任何内容,那么 ?.将跳过通话,我不需要?。让那里。

最佳答案

let()

fun <T, R> T.let(f: (T) -> R): R = f(this)

let() 是一个作用域函数:只要您想为代码的特定范围定义变量但不能超出范围,就可以使用它。让您的代码保持良好的独立性非常有用,这样您就不会“泄漏”变量:可以访问它们应该在的位置。

DbConnection.getConnection().let { connection ->
}

//连接在这里不再可见

let() 也可以用作针对 null 测试的替代方法:

val map : Map<String, Config> = ...
val config = map[key]
// config is a "Config?"
config?.let {
// This whole block will not be executed if "config" is null.
// Additionally, "it" has now been cast to a "Config" (no 
question mark)
}

A simple go to chart when to use when.

关于kotlin - 了解 Kotlin 的必要性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54382675/

相关文章:

swift - 懒让?结构中的快速解决方法

dictionary - Clojure 交换!不在 let 绑定(bind)中的映射函数内部工作

variables - 是否可以修改 let 绑定(bind)?

android - 使用 Fragments 实现 Compose 底部导航

kotlin - 尝试调用运行阻塞时,带有协同程序的Kotlin Vertx阻塞

android - Kotlin Android - 我的 fragment 中的数据绑定(bind)失败

postgresql - 如何清理 Spring Boot 应用程序中的数据库表?

haskell - 如何在Haskell中使用 "let"关键字定义多个变量

emacs - `let loop`(名为let)emacs lisp中的替代方案

android - 尝试在 Canary 5 上迁移