4

在 C++ 中,我只需要一个指向 arr[idx] 的指针(或引用)。
在 Scala 中,我发现自己创建了这个类来模拟指针语义。

class SetTo (val arr : Array[Double], val idx : Int) {
  def apply (d : Double) { arr(idx) = d }
}

没有更简单的方法吗?
Array 类没有返回对特定字段的某种引用的方法吗?

4

1 回答 1

9

Scala 中使用的数组是 JVM 数组(在 2.8 中),JVM 数组没有插槽引用的概念。

你能做的最好的就是你所说明的。但SetTo我觉得这不是一个好名字。ArraySlotArrayElement或者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)
于 2010-05-09T21:16:34.883 回答