首页 > 解决方案 > 为什么我不能在 Scala 中使用泛型类型约束?

问题描述

为什么我不能在 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] {

我希望在此对象中处理所有数字类型

标签: scalagenericstypesextendsgeneric-type-argument

解决方案


也许这接近你想要的?

import scala.reflect.ClassTag

//this is just a guess at what your Matrix might look like
class Matrix[A](val matrix :Array[Array[A]]) {
  val M:Int = matrix.length
  val N:Int = matrix.head.length
}

implicit class MatrixOps[T:Numeric:ClassTag](a :Matrix[T]) {
  val nOps = implicitly[Numeric[T]]
  import nOps._
  def +(that :Matrix[T]) :Matrix[T] = {
    if (that.M != a.M || that.N != a.N)
      throw new RuntimeException("Illegal matrix dimensions.")
    val c = Array.ofDim[T](a.M, a.N)
    for (i <- 0 until a.M)
      for (j <- 0 until a.N)
        c(i)(j) = a.matrix(i)(j) + that.matrix(i)(j)
    new Matrix(c)
  }
}

有了这个,您应该能够添加任何两个 Matrix 实例,只要尺寸和数字类型(IntFloat等)匹配。


推荐阅读