Scala 没有表示固定大小数组的类型。你可以简单地使用大小为 10 的数组——这是通常所做的——或者,如果你想要更强有力地保证它确实是大小为 10,你可以自己构造一个十长数组类:
class ArrayTen[T: ClassManifest](zero: T) {
protected val data = Array.fill(10)(zero)
def apply(i: Int) = data(i)
def update(i: Int, t: T) { data(i) = t }
protected def set(ts: Array[T]) { for (i <- data.indices) data(i) = ts(i) }
def map[U: ClassManifest](f: T => U) = {
val at = new ArrayTen(null.asInstanceOf[U])
at.set(data.map(f))
at
}
def foreach(f: T => Unit) { data.map(f) }
override def toString = data.mkString("#10[",",","]")
override def hashCode = scala.util.MurmurHash.arrayHash(data)
override def equals(a: Any) = a match {
case a: ArrayTen[_] => (data,a.data).zipped.forall(_ == _)
case _ => false
}
// Add other methods here if you really need them
}
例子:
scala> new ArrayTen("(nothing)")
res1: ArrayTen[java.lang.String] =
#10[(nothing),(nothing),(nothing),(nothing),(nothing),
(nothing),(nothing),(nothing),(nothing),(nothing)]
scala> res1(3) = "something!!!"
scala> res1
res3: ArrayTen[java.lang.String] =
#10[(nothing),(nothing),(nothing),something!!!,(nothing),
(nothing),(nothing),(nothing),(nothing),(nothing)]
如果您需要固定长度的数组来获取确定长度的参数,那么您应该
trait Size { size: Int }
class ArraySize[S <: Size, T: ClassManifest](zero: T, s: Size) {
protected val data = Array.fill(s.size)(zero)
...
}
除非您重新实现它们,否则您不会拥有所有集合的好东西,但是您又不想要大多数好东西,因为它们中的大多数都可以更改数组的长度。