什么是"::"在kotlin中意味着什么?

Win*_*er1 21 android kotlin

我是Kotlin的新手
我使用此代码打开另一个活动:

startActivity(Intent(this,IntroAndLang::class.java))
Run Code Online (Sandbox Code Playgroud)

当前的活动和目标活动都写在Kotlin中

我无法理解为什么没有单一的:,而不是::IntroAndLang::class.java

j2e*_*nue 22

::将kotlin函数转换为lambda.

假设你有一个看起来像这样的函数:

fun printSquare(a:Int) = println(a *2)
Run Code Online (Sandbox Code Playgroud)

现在假设你有一个将lambda作为第二个参数的类:

class MyClass(var someOtherVar:Any,var printSquare:(Int) -> Unit){

        fun doTheSquare(i:Int){
            printSquare(i)
        }
    }
Run Code Online (Sandbox Code Playgroud)

现在如何将printSquare函数传递给MyClass ??? 如果你尝试以下它不会工作:

  MyClass("someObject",printSquare) //printSquare is not a LAMBDA, its a function so it gives compile error of wrong argument
Run Code Online (Sandbox Code Playgroud)

那么我们如何将printSquare转换为lambda以便我们可以传递它?使用::符号.

MyClass("someObject",::printSquare) //now compiler does not compaint since its expecting a lambda and we have indeed converted printSquare FUNCTION into a LAMBDA. 
Run Code Online (Sandbox Code Playgroud)

另请注意,这是隐含的...意思this::printSquare is the same as ::printSquare.是如果printSquare函数在另一个类中像演示者那样说,那么你可以将它转换为lamba,如下所示:

presenter::printSquare
Run Code Online (Sandbox Code Playgroud)

更新:

这也适用于构造函数.如果你想转换一个对象的构造函数,然后将它转换为lambda,它就像这样:

(x,y)->MyObject::new
Run Code Online (Sandbox Code Playgroud)

这转化为MyObject(x,y)kotlin.

  • 我不太同意这个答案的措辞,因为在编程语言的上下文中,“lambda”(通常)指的是_anonymous_函数。另一方面,`::` 运算符(在本上下文中)创建对函数的_可调用引用_,即可用于稍后在代码中调用所述函数的名称。 (2认同)

s1m*_*nw1 17

文档中所述,这是一个类引用:

类引用:最基本的反射功能是获取Kotlin类的运行时引用.要获取对静态已知Kotlin类的引用,可以使用类文字语法:

val c = MyClass::class
//The reference is a value of type KClass.
Run Code Online (Sandbox Code Playgroud)

请注意,Kotlin类引用与Java类引用不同.要获取Java类引用,请在KClass实例上使用.java属性.

也是方法引用的语法,就像在这个简单的例子中一样:

list.forEach(::println)
Run Code Online (Sandbox Code Playgroud)

它指的是println在Kotlin标准库中定义的.

  • 尽管都使用了 `::`,`::println` 和 `IntroAndLang::class` 是无关的。方法引用无法计算为“KClass”,它不是 SAM 类型! (2认同)

use*_*816 14

:: 用于科特林的倒影

  1. 类参考 val myClass = MyClass::class
  2. 功能参考 list::isEmpty()
  3. 物业参考 ::someVal.isInitialized
  4. 构造函数参考 ::MyClass

有关详细阅读,请参见官方文档

  • 迄今为止最好的答案 (3认同)
  • @mohsen 同意。 (3认同)