1

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"

2
  • 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). Commented Jul 18, 2019 at 2:48
  • It's essentially equivalent. Use whichever you think reads better. Commented Jul 18, 2019 at 3:08

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.