【发布时间】:2019-09-24 12:06:13
【问题描述】:
我可能遗漏了一些东西,但我遇到了一个令人惊讶的不起作用的模式。
这里是:
object A {
def bar(func: (Int, Int) => Int): Int = 2
def bar(func: Int => Int): Int = 3
def foo(func: Int => Int): Int = 4
}
def f(n: Int) : Int = n + 1
val g: Int => Int = f
A.foo(f) // works fine
A.bar(f) // doesn't work
A.bar(g) // but this works
编译器要求我显式应用方法f以便通过它(写作f _):Unapplied methods are only converted to functions when a function type is expected.
我不明白为什么在将f 传递给A.foo 时隐式进行转换,但在传递给A.bar 时却没有。这可能与bar 有两个重载有关,但我不确定为什么?
我在 Scala 2.12.8 中使用 scalac。
【问题讨论】:
-
@francoisr 给出了正确答案,但如果您还想查看有关此问题的一些规范详细信息,请参阅this question 的答案。
-
@slouc 感谢您的链接。我将其添加到我的答案中
标签: scala