Scala将类型参数转换为Double

时间:2017-02-13 16:00:03

标签: scala

我定义了这个类:

var rows = new MLMatrix[Double](4)//now fill with Doubles
val le = new LinearEquations(y, rows)

其中

{{1}}

现在,在另一个类中,我正在创建对象LinearEquations(假设MLMatrix填充了双打):

{{1}}

我必须要进行某种类型的隐式转换,但我不知道该怎么做。构造函数接收一个类型参数,但是当我实现类时,我传递一个Double。

提前感谢,

2 个答案:

答案 0 :(得分:2)

代码:

10.0.abs

工作得益于隐式转换为RichDouble中定义的Predef类型:

@inline implicit def doubleWrapper(x: Double)   = new runtime.RichDouble(x)

然而,由于某些原因,编译器不能仅仅在某些情况下将T视为Double

虽然有这个问题的解决方案,例如类型类:

trait MathsOps[T] {

  def abs(num: T): T
}

implicit object DoubleOps extends MathOps[Double] {
   def abs(num: Double) = num.abs
}

class LinearEquations[T : MathsOps](var y: MLVector[T], var rows: MLMatrix[T]) {
def largestPivot(p: Int): Int = {
    var pivot = implicitly[MathOps[T]].abs(rows(p)(p))
    //more code
}

通过为您使用的所有T提供新的隐含,可以轻松扩展此功能。

要恢复语法,您可以定义另一个隐式类:

implicit class RichMathSyntax[T : MathOps](value: T) {

  def abs = implicitly[MathOps[T]].abs(value)
}

这适用于您可能希望传递到LinearEquations的任何数字类型。

答案 1 :(得分:0)

试试这个:

  class LinearEquations[T <% Double](var y: Array[Array[T]], var rows: Array[Array[T]]) {
    def largestPivot(p: Int): Int = {
      var pivot = rows(p)(p) //Error here: value abs is not a member of type parameter T
      val res: Double = scala.math.abs(pivot)
      //more code
      0
    }
  }

它为我编译