为什么推理引擎需要带有currying的显式类型

时间:2013-11-10 16:00:35

标签: scala currying

让我们定义f,一个支持currying的函数:

def f(a: Int)(b: Int) = a + b

此代码无法编译

def g= f(1)
<console>:10: error: missing arguments for method f;
follow this method with `_' if you want to treat it as a partially applied function
   def g= f(1)

我找到了这两个解决方法:

scala> def h = f(1) _
h: Int => Int

scala> def i : Int => Int = f(1)
i: Int => Int

但是我不明白为什么推理引擎需要帮助这样的小事?

1 个答案:

答案 0 :(得分:5)

这是因为def f(a: Int)(b: Int)不是函数,而是具有多个参数列表的方法。 Scala并没有将它们统一为一个概念,因此您也必须区分它们。

要部分应用具有多个参数列表的方法(因此隐式将此方法转换为函数),您必须在方法后添加下划线,如错误消息所示。当您明确告诉编译器您想要拥有哪个签名时,它还可以隐式地将方法转换为函数(如第二种解决方法中所示)。

如果你想在Scala中使用currying,最好从头开始创建一个函数:

scala> val f = (a: Int) => (b: Int) => a+b
f: Int => (Int => Int) = <function1>

scala> val g = f(1)
g: Int => Int = <function1>
相关问题