Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Constraint on generic class type

I am very new to Scala.

I want to implement a generic matrix class "class Matrix[T]". The only constraint on T should be that T should implement a "+" and a "*" mothod/function. How do I go about doing this?

For example I want to be able to use both Int, Double, and my own defined types e.g. Complex

I was thinking something along the lines:

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 
}

Everything type checks but I still can't instantiate a matrix. Am I missing an implicit constructor? How would I go about making that? Or am I completely wrong about my method?

Thanks in advance Troels

like image 246
Troels Blum Avatar asked Feb 16 '10 14:02

Troels Blum


1 Answers

You can use Numeric for Scala 2.8 for that. It is describe here. It would replace MatrixElement and its implementations:

class Matrix[T : Numeric](data: Array[Array[T]]) {
   def *(that: Matrix[T]) = //
}
like image 73
Thomas Jung Avatar answered Sep 23 '22 00:09

Thomas Jung