扩展scala基向量构造函数
只是学习scala,扩展基向量类有困难——我四处寻找构造函数签名,但无法解析文档。谁能告诉我写下面代码的正确方法吗?(无需进行错误检查)扩展scala基向量构造函数,scala,class,constructor,Scala,Class,Constructor,只是学习scala,扩展基向量类有困难——我四处寻找构造函数签名,但无法解析文档。谁能告诉我写下面代码的正确方法吗?(无需进行错误检查) VD类(x:Vector)扩展了Vector(x){ def+(that:VD)=that.foreach{case(e,i)=>that(i)+this(i)} } :12:错误:无法在对象$iw中访问类向量中的构造函数向量 谢谢 向量是最后一个类。它不能扩展。向量是最终类。它不能扩展。一种方法是使用,Scala本身广泛使用它来扩展基本类型。隐式转换是从S
VD类(x:Vector)扩展了Vector(x){
def+(that:VD)=that.foreach{case(e,i)=>that(i)+this(i)}
}
:12:错误:无法在对象$iw中访问类向量中的构造函数向量
谢谢 向量是最后一个类。它不能扩展。向量是最终类。它不能扩展。一种方法是使用,Scala本身广泛使用它来扩展基本类型。隐式转换是从Scala
Vector
到您自己的类(这里称为MyVector
)的转换,该类包含要添加的方法。然后,该方法返回一个普通的向量
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
编辑:
正如在注释中指出的,另一个优化是使用一个对象,而忽略伴随对象。另一个优化是使其成为一个新的应用程序
然后导入VectorStuff.\u
任何需要的地方。一种方法是使用,Scala本身广泛使用它来扩展基本类型。隐式转换是从ScalaVector
到您自己的类(这里称为MyVector
)的转换,该类包含要添加的方法。然后,该方法返回一个普通的向量
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
编辑:
正如在注释中指出的,另一个优化是使用一个对象,而忽略伴随对象。另一个优化是使其成为一个新的应用程序
然后导入VectorStuff.\u
您需要的任何地方。何时,如果您需要更多详细信息,您可以单击访问。该链接位于每页顶部附近。感谢您的回答和指导,当您需要更多详细信息时,它们是一个很大的帮助,您可以单击链接。链接在每一页的顶部。感谢您的回答和指导,这是一个很大的帮助。您可以提供到源代码的链接吗?从源代码(通过@jwvh链接)final class Vector[+a]private[不可变]…
您可以提供到源代码的链接吗?从源代码(通过@jwvh链接)final class Vector[+a]private[immutable]…
“隐式类”语法有助于简化样板文件。因此,隐式类MyVector[T](val底层:Vector[T]){…
“隐式类”语法有助于简化样板文件。因此,隐式类MyVector[T](val底层:Vector[T]){…