これを行う1つの方法は、"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)
も+
機能におけるジェネリックパラメータT
の追加を許可するように、いくつかのmagicを使用しています。
EDIT:コメントで指摘したように
、別の最適化が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._
です。
[ドキュメントを読む](http://www.scala-lang.org/api/current/#scala.collection.immutable.Vector$)、詳細が必要な場合は、[sourceコード](https://github.com/scala/scala/blob/v2.11.8/src/library/scala/collection/immutable/Vector.scala#L1)。リンクは各ページの上部にあります。 – jwvh
あなたの回答と指導をありがとう、彼らは大きな助けです – Iodizer