在 Scala 中,为什么我不能在没有明确指定参数类型的情况下部分应用函数?
这会产生一个匿名函数,正如您所期望的(f 是一个带有三个参数的函数):
This produces an anonymous function, as you would expect (f is a function with three arguments):
f(_, _, _)
我不明白的是为什么这不能编译,而是给出缺少参数类型"错误:
What I don't understand is why this doesn't compile, instead giving a "missing parameter type" error:
f(_, _, 27)
相反,我需要明确指定下划线的类型.鉴于 Scala 知道函数 f 的参数类型是什么,它难道不应该能够推断出它们吗?
Instead, I need to specify the types of the underscores explicitly. Shouldn't Scala be able to infer them given that it knows what the function f's parameter types are?
以下参考是 Scala 语言规范
考虑以下方法:
def foo(a: Int, b: Int) = 0
Eta Expansion 可以将其转换为 (Int, Int) => 类型的值.整数
.在以下情况下调用此扩展:
Eta Expansion can convert this to a value of type (Int, Int) => Int
. This expansion is invoked if:
a) _
用于代替参数列表(方法值(第 6.7 节))
a) _
is used in place of the argument list (Method Value (§6.7))
val f = foo _
b) 参数列表被省略,表达式的预期类型是函数类型(第 6.25.2 节):
b) the argument list is omitted, and expected type of expression is a function type (§6.25.2):
val f: (Int, Int) => Int = foo
c) 每个参数都是 _
(a 特殊情况匿名函数的占位符语法"(第 6.23 节)
c) each of the arguments is _
(a special case of the 'Placeholder Syntax for Anonymous Functions' (§6.23))
val f = foo(_, _)
表达式,foo(_, 1)
不符合 Eta 扩展的条件;它只是扩展为 (a) =>foo(a, 1)
(第 6.23 节).常规类型推断不会试图找出 a: Int
.
The expression, foo(_, 1)
doesn't qualify for Eta Expansion; it just expands to (a) => foo(a, 1)
(§6.23). Regular type inference doesn't attempt to figure out that a: Int
.