我想写一个SparseVector[T]
类(class)在哪里T
可以是 double 型、整数型或 bool 型。
该类不会由数组支持(因为我想要一个稀疏的数据结构),但是当我构建一个 AnyVal
的空数组时,我已经看到了这一点。类型,元素被初始化为默认值。例如:
scala> new Array[Int](10)
res0: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
scala> new Array[Boolean](10)
res1: Array[Boolean] = Array(false, false, false, false, false, false, false, false, false, false)
scala> new Array[Double](10)
res2: Array[Double] = Array(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
我怎样才能在我的类(class)中包含这个默认值?我想得到的行为是:
val v = new SparseVector[Double](100)
println( v(12) ) // should print '0.0'
val w = new SparseVector[Boolean](100)
println( v(85) ) // should print 'false'
谢谢
最佳答案
您可以向构造函数添加一个隐式参数作为第二个参数:
class SparseVector[A](size: Int) (implicit default: () => A) {
private var storage = scala.collection.mutable.Map[Int, A]()
def apply(i: Int) = storage.getOrElse(i, default())
def update(i: Int, v: A) = storage.update(i, v)
}
implicit def strDefault(): String = "default"
并为您关心的类型提供隐式。这也允许调用者通过传递他们自己的默认值来提供他们自己的默认值:
val sparseWithCustomDefault = new SparseVector[String](10) (() => "dwins rules!");
关于generics - 通用数据结构的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1848694/