【问题标题】:Why I can use the name of the a lambda expression, but not the name of the function? [duplicate]为什么我可以使用 lambda 表达式的名称,但不能使用函数的名称? [复制]
【发布时间】:2017-12-21 23:02:34
【问题描述】:

我可以使用“小”函数定义“大”函数:

fun apply3(a:Int, b:Int, c:Int, func: (Int,Int,Int)->Int ): Int{
    return func(a,b,c)
}

我可以这样称呼它:

println(apply3(1,2,3,{a,b,c->a+b+c}))

另一方面,如果我想多次使用同一个函数并为其命名,我就有问题了:

val plus1: (Int,Int,Int)->Int = {a,b,c->a+b+c}  //this is OK
...
fun plus2(a:Int, b:Int, c:Int)=a+b+c    // this too
...
println(apply3(1,2,3,plus1))    // this is allowed
...
println(apply3(1,2,3,plus2))    // this is NOT allowed

最后一行是禁止的。带留言:

Type mismatch
Required: (Int,Int,Int)->Int
Found: Int

为什么?对我来说,plus2 和 plus2 是一回事吗?

This post 有一个建议在我的情况下使用 ::plus2 的答案。这在技术上有所帮助,但不能解释这两个函数之间的区别。

【问题讨论】:

  • 此错误消息具有误导性并且明显损坏
  • @voddan 请看这里:stackoverflow.com/questions/47934397/…。我认为,这是更糟糕的问题。
  • @Gangnus 我有。有什么问题?我能提供什么帮助?
  • @voddan 我知道,Daniil,您是 Kotlin 社区的活跃人士?至少应该通过一些解释来涵盖对替代法的破坏。

标签: intellij-idea lambda functional-programming kotlin


【解决方案1】:

您需要使用function reference:

println(apply3(1,2,3,::plus2))

【讨论】:

  • 对不起,你自己让我改变了问题,这样你的答案就不再是答案了。但这对我来说是一个答案,并且确实有帮助。祝你圣诞快乐,新年快乐。请不要生气,我显然比你更理论化。 :-)
  • @Gangnus - 没问题 :)
猜你喜欢
  • 2015-11-28
  • 2014-07-21
  • 2016-08-14
  • 2019-11-14
  • 2016-07-21
  • 1970-01-01
  • 2016-03-28
  • 1970-01-01
  • 2014-07-24
相关资源
最近更新 更多