gpt4 book ai didi

kotlin - Kotlin 中的范围解析运算符

转载 作者:行者123 更新时间:2023-12-02 09:15:11 25 4
gpt4 key购买 nike

我已阅读以下语法。我不知道为什么在其中使用范围解析运算符。

class XyzFragment : Fragment() {

lateinit var adapter: ChatAdapter

override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
if (!::adapter.isInitialized) { <-- This one
adapter = ChatAdapter(this, arrayListOf())
}
}
}

我想知道 if (!::adapter.isInitialized) { 语句中的 :: 是什么。

最佳答案

:: 是 Kotlin 中 this:: 的缩写形式。

:: 是创建成员引用或类引用的运算符。例如,

class Test {        
fun foo() {

}

fun foo2(value: Int) {

}

fun bar() {
val fooFunction = ::foo
fooFunction.invoke() // equals to this.foo()
val foo2Function = ::foo2
foo2Function.invoke(1) // equals to this.foo2(1)
val fooFunction2 = Test::foo
val testObject = Test()
fooFunction2.invoke(this) // equals to this.foo()
fooFunction2.invoke(testObject) // equals to testObject.foo()
}
}

这个主要用于反射和传递函数。

关于kotlin - Kotlin 中的范围解析运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47899621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com