views:

128

answers:

1

In C++ I would just take a pointer (or reference) to arr[idx].
In Scala I find myself creating this class to emulate a pointer semantic.

class SetTo (val arr : Array[Double], val idx : Int) {
  def apply (d : Double) { arr(idx) = d }
}

Isn't there a simpler way?
Doesn't Array class have a method to return some kind of reference to a particular field?

+5  A: 

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)
Randall Schulz
Is there no default mutable.SeqRef or something like that? Really? Shouldn't we add it to standard library? I guess it could use mutable.Seq instead of Array.
Łukasz Lew
I like to use `:=` for `update`-like methods.
Alexey Romanov
@Alexy: That probably is better, from a readability standpoint. It crossed my mind that an implicit conversion could be used to read the value out of the referenced array slot, too.
Randall Schulz