了解Kotlin let的需求 [英] Understanding the need for Kotlin let

查看:76
本文介绍了了解Kotlin let的需求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图了解为什么需要让.在下面的示例中,我有一个带有功能GiveMeFive的Test类:

I'm trying to understand why let is needed. In the example below I have a class Test with a function giveMeFive:

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.鉴于在null引用上调用方法会跳过该调用并将x设置为null,为什么我需要使用let?在某些情况下只是?不能正常工作,需要租借吗?

x gets set to 5, then after test is set to null, calling either of the following statements return null for x. Given that calling a method on a null reference skips the call and sets x to null, why would I ever need to use let? Are some cases where just ?. won't work and let is required?

此外,如果所调用的函数未返回任何内容,则为?.会跳过该呼叫,并且我也不需要?.let.

Further, if the function being called doesn't return anything, then ?. will skip the call and I don't need ?.let there either.

推荐答案

let()

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

let()是作用域函数:只要您想为代码的特定范围定义变量,就可以使用它,但不能超出范围.保持代码自成一体非常有用,这样您就不会有变量泄漏":可以通过它们应有的位置进行访问.

let() is a scoping function: use it whenever you want to define a variable for a specific scope of your code but not beyond. It’s extremely useful to keep your code nicely self-contained so that you don’t have variables "leaking out": being accessible past the point where they should be.

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

//连接在这里不再可见

// connection is no longer visible here

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

let() can also be used as an alternative to testing against 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)
}

这篇关于了解Kotlin let的需求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆