Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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){ _, _ ->
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading