Search code examples
kotlinkotlin-multiplatform

Kotlin - Passing Trailing Lambdas- Function with two Parameter as Parameter


I am trying to learn function as parameter. My example could be false but in purpose of learning I try to do code below. I am getting

Type mismatch. Required: (Int, String) → String Found: () → String

What I try is to create "showNameAndAge" with two parameter(String and Int) required and pass it parameter in myMessage Func.

fun main() {
 myMessage(message = "Hello",1){
        showNameAndAge(2,"it")
    }
}

val showNameAndAge:(Int,String)->String={a,b-> "hello $a and $b" }

fun myMessage(message:String,a:Int,funAsParameter2:(Int,String)->String){ //trailing lamda
     println("$message + $a ${funAsParameter2(a,message)}")
}

Solution

  • Your code is almost correct, but you need to provide names for parameters received inside the lambda:

    myMessage(message = "Hello",1){ p1, p2 ->
        showNameAndAge(2,"it")
    }
    

    If you don't use these arguments inside lambda, you can use _ as their names:

    myMessage(message = "Hello",1){ _, _ ->