在Lambda中调用函数与函数引用之间的区别

时间:2019-07-18 02:37:52

标签: kotlin function-reference

在以下代码中(在kotlin中)

fun greet(){
    print("Hello!  ")
}
fun salute(){
    print("Have a nice day ")
}


fun main(args: Array<String>){

    //val todoList: List<()->Unit> = listOf(::greet,::salute)
    val todoList: List<()->Unit> = listOf({greet()},{salute()})

    for(task in todoList){
        task()
    }    
}

使用现在注释的第一种方法(函数引用)相对于使用第二种方法(仅在lambda中调用函数)有什么意义

到目前为止,结果都显示“你好!祝你有美好的一天”

1 个答案:

答案 0 :(得分:1)

enter image description here

您可以根据自己的想法检查签名。

::是反映从方法获取KFunction类型的操作

val f2 = {greet()}是:您创建了一个新的lambda语句 像

() ->  () -> Unit  

然后调用内陆λ

相关问题