Home > database >  Kotlin - Passing Trailing Lambdas- Function with two Parameter as Parameter
Kotlin - Passing Trailing Lambdas- Function with two Parameter as Parameter

Time:02-06

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)}")
}

CodePudding user response:

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){ _, _ ->
  • Related