在 C++ 中,我只需要一个指向 arr[idx] 的指针(或引用)。
在 Scala 中,我发现自己创建了这个类来模拟指针语义。
class SetTo (val arr : Array[Double], val idx : Int) {
def apply (d : Double) { arr(idx) = d }
}
没有更简单的方法吗?
Array 类没有返回对特定字段的某种引用的方法吗?
最佳答案
Scala 中使用的数组是 JVM 数组(在 2.8 中)并且 JVM 数组没有槽引用的概念。
你能做的最好的就是你所说明的。但是SetTo
不会让我觉得是个好名字。 ArraySlot
, ArrayElement
或 ArrayRef
看起来更好。
此外,您可能想要实现 apply()
读取插槽和 update(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, 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)
关于arrays - 如何在 Scala 中获得 Ponter/Reference 语义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2799128/