【问题标题】:Why can't I use a generic type constraint in Scala? [closed]为什么我不能在 Scala 中使用泛型类型约束? [关闭]
【发布时间】: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 &lt;: 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


【解决方案1】:

也许这接近你想要的?

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)
  }
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-22
    • 2019-03-31
    • 1970-01-01
    • 2011-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多