我是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.
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标准库中定义的.
| 归档时间: |
|
| 查看次数: |
7178 次 |
| 最近记录: |