【问题标题】:Passing function to overloaded method in Scala将函数传递给Scala中的重载方法
【发布时间】:2016-03-02 09:24:31
【问题描述】:

在将函数引用传递给 Scala 中的重载方法时遇到了一个有趣的问题(使用 2.11.7)

以下代码按预期工作

def myFunc(a: Int, b: String): Double = {
  a.toDouble + b.toDouble
}


def anotherFunc(value: String, func: (Int, String) => Double) = {
  func(111, value)
}

anotherFunc("123123", myFunc)

但是下面的代码不能编译

def myFunc(a: Int, b: String): Double = {
  a.toDouble + b.toDouble
}


def anotherFunc(value: String, func: (Int, String) => Double) = {
  func(111, value)
}

def anotherFunc(value: Int, func: (Int, String) => Double) = {
  func(value, "123123")
}

anotherFunc("123123", myFunc)

编译器喊如下

scala> anotherFunc("123123", myFunc)
<console>:13: error: type mismatch;
 found   : String("123123")
 required: Int
       anotherFunc("123123", myFunc)

【问题讨论】:

    标签: scala


    【解决方案1】:

    你在使用 Scala REPL 吗?它的设计决策之一是,如果您定义了两个具有相同名称的变量/函数,则“最后定义的获胜”。在您的情况下,它是一个带有 Int 参数的函数。

    您可以使用以下命令打印 REPL 中所有已定义的符号:

    $intp.definedTerms.foreach(println)
    

    这里有人有类似的问题:Why its possible to declare variable with same name in the REPL?

    【讨论】:

    • 虽然行为不同 - 上面的代码在类文件中也失败了,而不仅仅是 REPL。它拒绝编译。我将编辑我的问题以反映这一事实。
    【解决方案2】:

    我不知道原因,但似乎你必须写

    anotherFunc("123123", myFunc _)
    

    让它工作。

    【讨论】:

    • 很想知道为什么在这种情况下需要部分应用程序
    猜你喜欢
    • 1970-01-01
    • 2019-06-19
    • 2013-03-05
    • 1970-01-01
    • 2015-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-20
    相关资源
    最近更新 更多