【发布时间】:2019-05-25 11:45:29
【问题描述】:
我一直在想,为什么这段代码不能编译?
Scala 中有没有一种方法可以创建通用参数化的方法/函数,并允许像“reduce”这样的操作。
这种行为是否与类型擦除有任何共同之处,还是其他?我希望看到对此的广泛解释:)
def func2[B <: Int](data: Seq[B]): Unit = {
val operation = (a: B, b: B) => a.-(b)
data.reduce(operation)
}
编译器说:
type mismatch;
found : (B, B) => Int
required: (Int, Int) => Int
此外,本着同样的精神 - 总体上是否可以使用此方法在参数化集合上调用任何“类流”方法:
def func2[B <: Int](data: Seq[B]): Unit = {
val operation = (a: B, b: B) => a.-(b)
data.sum
}
也给出:
could not find implicit value for parameter num: Numeric[B]
【问题讨论】:
-
class
Int是final,你可以创建Int的子类