【发布时间】:2020-09-10 19:59:17
【问题描述】:
为什么我不能在 Scala 中使用泛型类型约束? 这是我的代码
abstract class Adder[T]{
def +(a: Matrix[T], that: Matrix[T]): Matrix[T]
def *(a: Matrix[T], that: Matrix[T]): Matrix[T]
def show(a: Matrix[T]): Unit
}
object Adder{
implicit object TDouble extends Adder[T <: Double] {
override def +(a: Matrix[T], that: Matrix[T]): Matrix[T] = {
if (that.M != a.M || that.N != a.N) throw new RuntimeException("Illegal matrix dimensions.");
var C = Array.ofDim[T](a.M,a.N);
for (i <- 0 to a.M - 1)
for (j <- 0 to a.N - 1){
C(i)(j) = a.matrix(i)(j) + that.matrix(i)(j);
}
new Matrix(C)
}
}
}
这是错误
scala:11: error: ']' expected but ':' found.
implicit object TDouble extends Adder[T: <: Double] {
我希望在这个对象中处理所有数值类型
【问题讨论】:
-
贴出的代码不完整,有很多错误。如果您“希望处理所有数字类型”,那么
[T <: Double]不会这样做。 (事实上,这不会做任何事情。)您需要使用Numeric类型类。 -
欢迎来到 Stack Overflow。您的问题
Why can't I use a generic type constraint in Scala?太宽泛,然后似乎会导致问题陈述由您以外的其他人解决……尝试提出一个具体问题。看看How do I ask a good question?,尤其是How to create a Minimal, Reproducible Example。最后,Stack Overflow 不应该替代优秀的在线教程和书籍(关于 Scala)。 -
错误信息与“不能使用泛型类型约束”无关。这只是一个微不足道的错字。
标签: scala generics types extends generic-type-argument