Kotlin:IT 和 THIS 关键字之间的区别

Har*_*hah 16 android kotlin

在一次 kotlin 采访中,有人问我it&this关键字之间的区别。

我在谷歌上搜索过,但无法找到问题的正确答案。

有人可以指导我这两者之间的实际区别是什么?

我知道这是非常基本的问题,我是 kotlin 的新手。

Sae*_*ari 8

您需要了解作用域函数

Kotlin 标准库包含几个函数,其唯一目的是在对象的上下文中执行代码块。当您在提供 lambda 表达式的对象上调用此类函数时,它会形成一个临时作用域。

在这个范围内有一个Context对象要么是this要么it

在示波器功能runapply并且with范围(临时)变更为您在调用此函数的对象的范围:

val str = "Hello"
str.run {
    //Here this refers to str
}
Run Code Online (Sandbox Code Playgroud)

在 Scope 函数中letalso作用域没有改变(与调用者作用域保持一致),但你的 lambda 会像it在 lambda 内部一样接收上下文:

val str = "Hello"
str.let {
    //Here it refers to str
}
Run Code Online (Sandbox Code Playgroud)

您可以查看链接以获取更多信息。


Ten*_*r04 8

it仅在具有单个参数的 lambda 内相关。它是单个参数的默认名称,是允许您省略单个参数命名的简写。以这种方式声明的函数可能如下所示:

(String) -> Unit
Run Code Online (Sandbox Code Playgroud)

在 lambda 中,this是接收者参数。它仅在函数定义为具有接收器时才有效,如下所示:

String.() -> Unit
Run Code Online (Sandbox Code Playgroud)

如果函数声明没有接收器,this则与它在 lambda 范围之外的含义相同。对于扩展函数,它是扩展函数的接收者。否则,它是包含该函数的类。


Jee*_*ede 7

itthis关键字之间的区别可以通过 lambda 方法接收器(又名高阶函数)的示例来解释。

假设您已经编写了一个函数或使用了一个为您提供回调作为 lambda 方法接收器的函数。像这样的东西:() -> Unit

因此,您希望回调的方式有两种可能:

  1. 向回调提供参数

    • 回调参数意味着您希望为回调提供一个调用者可以在调用时使用的参数,也被视为it

上面写的只是意味着:(Int) -> Unit。该函数方法参数可以在调用时为您提供整数。

查看下面的片段:

fun someMethodWithCallback(callback: (Int) -> Unit) {
    callback(0)
}

// On the time of consumption, the `Int` parameter by default exposed to callback as it parameter.
obj.someMethodWithCallback { it -> // Here it is the method parameter of callback that we passed, you can also rename it to any other named value
    // it can be directly used as Int value if needed or you can rename it at receiver above
}
Run Code Online (Sandbox Code Playgroud)

注意:您可以向回调提供多个参数,然后您将无法接收,而是回调会为您提供传递的变量数量。

  1. 提供回调对象

    • 提供回调的另一种方法是提供对象本身作为回调参数。这意味着回调语法略有变化,并为您提供对象本身作为回调参数this

上面写的只是意味着:Int.() -> Unit。该函数方法对象可以在调用时为您提供整数。

查看下面的片段:

fun someMethodWithCallback(callback: Int.() -> Unit) {
    callback(0)
}

// On the time of consumption, the `Int` parameter by default exposed to callback as it parameter.
obj.someMethodWithCallback { this // Here this is the method object of callback that we passed, you can not rename it to anything else
    // it can be used as Int value by referencing as this
}
Run Code Online (Sandbox Code Playgroud)

希望它有意义!