2

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"

KansaiRobot
  • 7,564
  • 11
  • 71
  • 150
  • In this case it's not better. In general: 1) Fewer brackets (in more complicated expressions you will fill it). 2) For functions with multiple arguments you won't need to re-pass them, so you will win some space (and your expression will become simpler). –  Jul 18 '19 at 02:48
  • It's essentially equivalent. Use whichever you think reads better. – Louis Wasserman Jul 18 '19 at 03:08

1 Answers1

1

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

JsonSong
  • 328
  • 2
  • 14