Not an array, but a single, immutable IndexedSeq implementation that I recently compiled. I followed the example given here where they implement the RNA class. Between this example, ScalaDocs and a lot of “useful” compiler errors, I managed to configure it correctly. The fact that OneBasedSeq is generalized made it a little more complicated than the RNA example. In addition to the extended attributes and methods overridden in the example, I had to extend IterableLike and override the iterator method, because various methods call this method behind the scenes, and the default iterator is based on zero.
Please forgive any stylistic or idiomatic quirks; I have been programming in Scala for less than 2 months.
import collection.{IndexedSeqLike, IterableLike} import collection.generic.CanBuildFrom import collection.mutable.{Builder, ArrayBuffer} // OneBasedSeq class final class OneBasedSeq[T] private (s: Seq[T]) extends IndexedSeq[T] with IterableLike[T, OneBasedSeq[T]] with IndexedSeqLike[T, OneBasedSeq[T]] { private val innerSeq = s.toIndexedSeq def apply(idx: Int): T = innerSeq(idx - 1) def length: Int = innerSeq.length override def iterator: Iterator[T] = new OneBasedSeqIterator(this) override def newBuilder: Builder[T, OneBasedSeq[T]] = OneBasedSeq.newBuilder override def toString = "OneBasedSeq" + super.toString } // OneBasedSeq companion object object OneBasedSeq { private def fromSeq[T](s: Seq[T]) = new OneBasedSeq(s) def apply[T](vals: T*) = fromSeq(IndexedSeq(vals: _*)) def newBuilder[T]: Builder[T, OneBasedSeq[T]] = new ArrayBuffer[T].mapResult(OneBasedSeq.fromSeq) implicit def canBuildFrom[T, U]: CanBuildFrom[OneBasedSeq[T], U, OneBasedSeq[U]] = new CanBuildFrom[OneBasedSeq[T], U, OneBasedSeq[U]] { def apply() = newBuilder def apply(from: OneBasedSeq[T]): Builder[U, OneBasedSeq[U]] = newBuilder[U] } } // Iterator class for OneBasedSeq class OneBasedSeqIterator[T](private val obs: OneBasedSeq[T]) extends Iterator[T] { private var index = 1 def hasNext: Boolean = index <= obs.length def next: T = { val ret = obs(index) index += 1 ret } }
Karl von L
source share