Scala:泛型类类型的约束

Tro*_*lum 7 generics scala scala-2.8

我是Scala的新手.

我想实现一个通用矩阵类"class Matrix [T]".对T的唯一约束应该是T应该实现"+"和"*"方法/函数.我该怎么做呢?

例如,我希望能够同时使用Int,Double和我自己定义的类型,例如Complex

我正在思考一些事情:

class Matrix[T <: MatrixElement[T]](data: Array[Array[T]]) {
   def *(that: Matrix) = ..// code that uses "+" and "*" on the elements
}
abstract class MatrixElement[T] {
    def +(that: T): T
    def *(that: T): T 
}
implicit object DoubleMatrixElement extends MatrixElement[Double]{
    def +(that: Double): Double = this + that
    def *(that: Double): Double = this * that 
}
implicit object ComplexMatrixElement extends MatrixElement[Complex]{
    def +(that: Complex): Complex = this + that
    def *(that: Complex): Complex = this * that 
}
Run Code Online (Sandbox Code Playgroud)

所有类型检查但我仍然无法实例化矩阵.我错过了隐式构造函数吗?我该怎么做呢?或者我对我的方法完全错了?

在此先感谢Troels

Tro*_*lum 4

终于找到了答案:-)我想我的第一次尝试并没有那么遥远。就这样:(为 scala 2.8 编写)

trait MatrixElement[T] {
    def +(that: T): T
    def *(that: T): T 
}

object MatrixElement {
    implicit def intToMatrixElement(x : Int) = new MatrixElement[Int] {
        def +(y : Int) = x + y
        def *(y : Int) = x * y
    }
    implicit def doubleToMatrixElement(x : Double) = new MatrixElement[Double] {
        def +(y : Double) = x + y
        def *(y : Double) = x * y
    }
    implicit def complexToMatrixElement(x : Complex) = new MatrixElement[Complex] {
        def +(y : Complex) = x + y
        def *(y : Complex) = x * y
    }
}

class Matrix[T  <% MatrixElement[T] : ClassManifest ](d: Array[Array[T]]) {
    def *(that: Matrix) = ..// code that uses "+" and "*" on the elements
}
Run Code Online (Sandbox Code Playgroud)

现在我可以做这样的事情:

scala> new Matrix(Array(Array(1,0),Array(0,1)))
res0: Matrix[Int] = 
1 0 
0 1 

scala> new Matrix(Array(Array(new Complex(0),new Complex(1)),Array(new Complex(1),new Complex(0))))
res9: Matrix[Complex] = 
(0.0,0.0i) (1.0,0.0i) 
(1.0,0.0i) (0.0,0.0i) 
Run Code Online (Sandbox Code Playgroud)