Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Ponter/Reference semantics in Scala

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?

like image 382
Łukasz Lew Avatar asked Jan 23 '23 02:01

Łukasz Lew


1 Answers

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)
like image 151
Randall Schulz Avatar answered Jan 30 '23 00:01

Randall Schulz