英文:
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)}")
}
英文:
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)}")
}
答案1
得分: 1
你的代码几乎正确,但你需要为 Lambda 内部接收的参数提供名称:
myMessage(message = "Hello", 1){ p1, p2 ->
showNameAndAge(2, "it")
}
如果你在 Lambda 内部不使用这些参数,你可以使用 _
作为它们的名称:
myMessage(message = "Hello", 1){ _, _ ->
英文:
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){ _, _ ->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论