我已阅读以下语法。我不知道为什么会使用范围分辨率运算符。
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) {
是什么。
先谢谢
答案 0 :(得分:3)
::
是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()
}
}
这主要用于反射和传递函数。