Arrays used in Scala are JVM arrays (in 2.8) and JVM arrays have no concept of a slot reference.
The best you can do is what you illustrate. But SetTo
does not strike me as a good name. ArraySlot
, ArrayElement
or ArrayRef
seem better.
Furthermore, you might want to implement apply()
to read the slot and update(newValue)
to replace the slot. That way instances of that class can be used on the left-hand-side of an assignment. However, both retrieving the value via apply
and replacing it via update
method will require the empty argument lists, ()
.
class ASlot[T](a: Array[T], slot: Int) {
def apply(): T = a(slot);
def update(newValue: T): Unit = a(slot) = newValue
}
scala> val a1 = Array(1, 2, 3)
a1: Array[Int] = Array(1, 2, 3)
scala> val as1 = new ASlot(a1, 1)
as1: ASlot[Int] = ASlot@e6c6d7
scala> as1()
res0: Int = 2
scala> as1() = 100
scala> as1()
res1: Int = 100
scala> a1
res2: Array[Int] = Array(1, 100, 3)