Difference between calling a function in a lambda and function references

224 views Asked by At

In the following code (in 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()
    }    
}

What is the significance of using the first way that is now commented (Function references) against using the second way (just calling the functions in a lambda)

As far of results both print "Hello! Have a nice day"

1

There are 1 answers

0
JsonSong On

enter image description here

you can check the signature by your ide .

:: is reflect operation to get KFunction type from method

val f2 = { greet() } is that : you create a new lambda statement like

() ->  () -> Unit  

and then call the inland lambda