简体   繁体   English

具有通用类型的Scala重载运算符

[英]Scala overloading operators with generic types

I am doing a project in scala and i am struggling with a certain thing. 我正在斯卡拉(Scala)做一个项目,正在为某件事而苦苦挣扎。 I am making a matrix DSL so i am overloading some operators like +,- or * so that i can do : 我正在制作矩阵DSL,所以我要重载一些运算符,例如+,-或*,以便我可以这样做:

matrixMult = matrix1*matrix2

The thing is i made this class where the matrix was represented as a Array[Array[Double]] type but i would like to make it generic: Array[Array[T]] 事情是我做成了此类,其中矩阵表示为Array [Array [Double]]类型,但我想使其通用:Array [Array [T]]

The thing is i do not know how to handle this in the class methods since for operations like +,- and *. 事情是我不知道如何在类方法中处理此问题,因为对于+,-和*等操作。 It should work for doubles or ints, but strings should throw an error. 它应该适用于双精度或整数,但是字符串应该引发错误。 Here is my current code: 这是我当前的代码:

  def +(other : Matrix[Double]): Matrix[Double] = {
  var array = new Array[Array[Double]](rows)
  for (i <- 0 to (rows - 1)) {
    var arrayRow = new Array[Double](columns)
    for (j <- 0 to (columns - 1)) {
      arrayRow(j) = this.array(i)(j) + other.array(i)(j)
    }
    array(i) = arrayRow
  }
  return new Matrix(array)

} }

I get an error on the arrayRow(j) =... line which is normal because it does not know what type the "this" object is. 我在arrayRow(j)= ...行上收到错误,这是正常的,因为它不知道“ this”对象的类型。 What should i do to make this work? 我应该怎么做才能使这项工作? Like i would like this method only to be accessible to doubles (or ints) and not strings, if this method was to be invoked on a Matrix[String] object it should throw an error. 就像我希望此方法只能被双精度(或整数)访问,而不是字符串可访问,如果要在Matrix [String]对象上调用此方法,则应抛出错误。 I tried pattern matching with isInstanceOf() but that doesn't remove the error and i can't compile. 我尝试了与isInstanceOf()进行模式匹配,但这并不能消除错误,而且我无法编译。

If kind of have the same issue with all of my methods in my class, so i'd like a generic answer if possible. 如果我的课程中的所有方法都存在相同的问题,那么如果可能的话,我希望有一个通用的答案。

Any help is appreciated, Thank you very much! 任何帮助表示赞赏,非常感谢!

Not sure which version of Scala you are using, but if you're on 2.8, I found this thread on Scala-lang, and it looks like you may be able to use T:Numerics to limit it to Int, Long, Float, Double. 不知道您使用的是哪个版本的Scala,但是如果您使用的是2.8,则我在Scala-lang上找到了该线程,看来您可以使用T:Numerics将其限制为Int,Long,Float,双。

A little farther down in the thread, to limit it to JUST a subset of those (like Int, Double), they say to define your own generic Trait. 他们说要定义自己的通用Trait,将其限制在线程的一个子集(如Int,Double)中。 https://www.scala-lang.org/old/node/4787 https://www.scala-lang.org/old/node/4787

Answer can be found in comments: 答案可以在评论中找到:

Matrix addition has been asked, and answered, before. 矩阵加法已被问及回答。 Even though the question posses a different matrix implementation, I believe the answer from the redoubtable Rex Kerr is still applicable. 尽管问题提出了不同的矩阵实现方式,但我认为可重制的Rex Kerr的答案仍然适用。 – jwvh – jwvh

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM