为什么 Scala 不推断部分应用函数的类型?
Why scala does not infer type in partially applied function?
考虑到 scala 的类型推断,我希望以下操作不会失败:
scala> def partiallyApplied(x: Int, y: Int, z: Int) = x + y + z
partiallyApplied: (x: Int, y: Int, z: Int)Int
scala> val partialSum = partiallyApplied(2, 3, _)
<console>:11: error: missing parameter type for expanded function ((x) => partiallyApplied(2, 3, x))
val partialSum = partiallyApplied(2, 3, _)
^
当然,这行得通:
scala> val partialSum = partiallyApplied(2, 3, _:Int)
partialSum: Int => Int = <function1>
在这种情况下,类型推断对部分应用函数没有帮助有什么原因吗?
Scala specification 确切说明了在哪些情况下可以省略参数类型,这不是其中之一:
If the expected type of the anonymous function is of the shape scala.FunctionN[S1,…,Sn, R]
, or can be SAM-converted to such a function type, the type
Ti
of a parameter
xi
can be omitted, as far as
Si
is defined in the expected type, and
Ti = Si
is assumed. Furthermore, the expected type when type checking e
is R
.
If there is no expected type for the function literal, all formal parameter types Ti
must be specified explicitly, and the expected type of e
is undefined. The type of the anonymous function is scala.FunctionN[T1,…,Tn, R]
, where R
is the packed type of e
. R
must be equivalent to a type which does not refer to any of the formal parameters xi
.
是否可以将其更改为也适用于这种特定情况?当然。改变是否值得?可能不是。
考虑到 scala 的类型推断,我希望以下操作不会失败:
scala> def partiallyApplied(x: Int, y: Int, z: Int) = x + y + z
partiallyApplied: (x: Int, y: Int, z: Int)Int
scala> val partialSum = partiallyApplied(2, 3, _)
<console>:11: error: missing parameter type for expanded function ((x) => partiallyApplied(2, 3, x))
val partialSum = partiallyApplied(2, 3, _)
^
当然,这行得通:
scala> val partialSum = partiallyApplied(2, 3, _:Int)
partialSum: Int => Int = <function1>
在这种情况下,类型推断对部分应用函数没有帮助有什么原因吗?
Scala specification 确切说明了在哪些情况下可以省略参数类型,这不是其中之一:
If the expected type of the anonymous function is of the shape
scala.FunctionN[S1,…,Sn, R]
, or can be SAM-converted to such a function type, the typeTi
of a parameterxi
can be omitted, as far asSi
is defined in the expected type, andTi = Si
is assumed. Furthermore, the expected type when type checkinge
isR
.If there is no expected type for the function literal, all formal parameter types
Ti
must be specified explicitly, and the expected type ofe
is undefined. The type of the anonymous function isscala.FunctionN[T1,…,Tn, R]
, whereR
is the packed type ofe
.R
must be equivalent to a type which does not refer to any of the formal parametersxi
.
是否可以将其更改为也适用于这种特定情况?当然。改变是否值得?可能不是。