在C中,我只需要指向arr [idx]的指针(或引用).
在 Scala中,我发现自己创建了这个类来模拟指针语义.
在 Scala中,我发现自己创建了这个类来模拟指针语义.
class SetTo (val arr : Array[Double],val idx : Int) { def apply (d : Double) { arr(idx) = d } }
解决方法
Scala中使用的数组是JVM数组(2.8),JVM数组没有插槽引用的概念.
你能做的最好就是你所说的.但SetTo并没有把我当成一个好名字. ArraySlot,ArrayElement或ArrayRef似乎更好.
此外,您可能希望实现apply()来读取插槽并更新(newValue)以替换插槽.这样,该类的实例可以在赋值的左侧使用.但是,通过apply检索值并通过update方法替换它都需要空参数列表().
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,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)