How to get Ponter/Reference semantics in Scala
Asked Answered
D

1

5

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?

Despond answered 9/5, 2010 at 20:51 Comment(0)
A
9

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)
Araldo answered 9/5, 2010 at 21:16 Comment(2)
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.Acosta
@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.Araldo

© 2022 - 2024 — McMap. All rights reserved.