扩展scala base Vector构造函数

时间:2016-08-22 02:32:16

标签: scala class constructor

只是学习scala并且无法扩展基础向量类 - 我四处寻找构造函数签名但无法解析文档。谁能告诉我编写下面代码的正确方法? (无需检查错误)

class VD(x: Vector) extends Vector(x){
       def +(that: VD) = that.foreach{ case (e,i) => that(i)+this(i)}
       }
<console>:12: error: constructor Vector in class Vector cannot be accessed in object $iw

谢谢!

2 个答案:

答案 0 :(得分:3)

执行此操作的一种方法是使用"rich wrapper",Scala本身会广泛使用它来扩展基本类型。从Scala Vector到您自己的类(此处称为MyVector)进行隐式转换,其中包含您要添加的方法。然后该方法返回普通Vector

class MyVector[T](val underlying: Vector[T]) {
  def +(that: Vector[T])(implicit x: scala.math.Numeric[T]): Vector[T] = {
    import x._
    underlying.zip(that).map {
      case (a,b) => a + b
    }
  }
}

object MyVector {
  implicit def toMyVector[T](that: Vector[T]): MyVector[T] = new MyVector(that)
}

import MyVector._

val a = Vector(1, 2, 3)
val b = Vector(4, 5, 6)
val c = a + b

输出:

a: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3)
b: scala.collection.immutable.Vector[Int] = Vector(4, 5, 6)
c: Vector[Int] = Vector(5, 7, 9)

还使用一些magic来允许在T函数中添加通用参数+

编辑:

正如评论中指出的,另一个优化是使用implicit class并省略伴随对象。另一个优化是将其设为value class

object VectorStuff {
  implicit class MyVector[T](val underlying: Vector[T]) extends AnyVal {
    def +(that: Vector[T])(implicit x: scala.math.Numeric[T]): Vector[T] = {
      import x._
      underlying.zip(that).map {
        case (a, b) => a + b
      }
    }
  }
}

然后import VectorStuff._,无论您需要它。

答案 1 :(得分:1)

Vector是最后一堂课。它不能扩展。