I am trying to do the following...
I have a class defined as RefInt
and a method refInt5
which should take a List
of references to instances of RefInt
.
I need to change the argument in such a way so that it becomes visible to the caller.
object argpass {
class RefInt (initial : Int) {
private var n : Int = initial
def get () : Int = n
def set (m : Int) : Unit = { n = m }
}
def refint5 (xs : List[RefInt]) : Unit = {
// What am I missing to modify RefInt(s)?
}
}
The test code I have to see if the argument has changed.
property ("EX05 - refint5", EX (5)) {
val rand = scala.util.Random
val xs : List[Int] = (1 to 5).toList.map (x => rand.nextInt (100))
val ys : List[RefInt] = xs.map (x => new RefInt (x))
refint5 (ys)
var changed = false
for ((x, r) <- xs.zip (ys)) {
if (x != r.get) {
changed = true
}
}
if (!changed) {
throw new RuntimeException ("xs is unchanged!")
}
}
}
One possible option: Iterate xs
, call set
for each element - get the current value - add 1.
def refint5(xs: List[RefInt]): Unit = {
xs.foreach { x => x.set(x.get + 1) }
}