Kotlin – 传递尾随 Lambda – 将带有两个参数的函数作为参数

huangapple go评论49阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年2月6日 08:06:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75356368.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定