Łuk*_*Lew 4 arrays pointers scala reference scala-2.8
在C++中,我只需要指向arr [idx]的指针(或引用).
在Scala中,我发现自己创建了这个类来模拟指针语义.
class SetTo (val arr : Array[Double], val idx : Int) {
def apply (d : Double) { arr(idx) = d }
}
Run Code Online (Sandbox Code Playgroud)
有没有更简单的方法?
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)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4567 次 |
最近记录: |