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
ありがとう!
回答:
回答№1の場合は3これを行う1つの方法は、 「リッチラッパー」、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
の中に +
関数。
編集:
コメントで指摘されているように、別の最適化は、 暗黙のクラス コンパニオンオブジェクトを省略します。さらに別の最適化はそれをすることです 値クラス.
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._
あなたがそれを必要とするどこにでも。
回答№2の場合は1
Vectorは最終クラスです。拡張できません。