您的问题是 square 不是函数(即 scala.Function1[T, T] aka (T) => T)。相反,它是一个类型参数化的方法,具有多个参数列表,其中一个是隐式的……Scala 中没有语法来定义完全等效的函数。
有趣的是,您对 Numeric 类型类的使用意味着 Scala 中高级函数的通常编码不直接适用于此,但我们可以将它们调整到这种情况并得到类似的东西,
trait HigherRankedNumericFunction {
def apply[T : Numeric](t : T) : T
}
val square = new HigherRankedNumericFunction {
def apply[T : Numeric](t : T) : T = implicitly[Numeric[T]].times(t, t)
}
这给了我们一个更高级别的“函数”,它的类型参数上下文绑定到数值,
scala> square(2)
res0: Int = 4
scala> square(2.0)
res1: Double = 4.0
scala> square("foo")
<console>:8: error: could not find implicit value for evidence parameter of type Numeric[java.lang.String]
square("foo")
我们现在可以用 HigherRankedNumericFunctions 定义 两次,
def twice[T : Numeric](f : HigherRankedNumericFunction, a : T) : T = f(f(a))
scala> twice(square, 2)
res2: Int = 16
scala> twice(square, 2.0)
res3: Double = 16.0
这种方法的明显缺点是您失去了 Scala 的单态函数字面量的简洁性。