Kotlin + let方法+此关键字

问题描述 投票:1回答:1

[Venkat在他的书《 Kotlin中的编程》第237页上解释了流畅方法Also(),apply(),let()和run()之间的区别

但是列出的代码无法编译。

特别是这两个调用:编译器说"'this' is not defined in this context"

val result1 = str.let { arg ->
    print(String.format(format, "let", arg, this, result))
    result
}
println(String.format("%-10s", result1))

val result2 = str.also { arg ->
    print(String.format(format, "also", arg, this, result))
    result
}
println(String.format("%-10s", result2))

所以我的问题是:let()和Also()是否支持'this'关键字。

kotlin
1个回答
2
投票

如果您查看let的源功能:

public inline fun <T, R> T.let(block: (T) -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return block(this)
}

您将看到带有一个参数的lambda。因此,要使用该参数,可以使用it

如果在let中调用this,它将引用调用该函数的类的范围:

class Clazz {

  fun function() {
     something.let {
        // `this` refers to class scope, so `this` is a Clazz
        // `it` refers to the something itself
     }
  }
}

also相同。

alsolet之间的区别在于它们的返回方式。 let返回块返回的内容,also将返回对象本身,而且let使用lambda作为参数,因此可以使用it访问该参数,而also使用lambda接收器] >,使参数可以通过this进行访问。

TL; DR

let中,关键字this将引用其所属的类。因此,如果它不在课程中,那么它将什么也没有引用。

© www.soinside.com 2019 - 2024. All rights reserved.