加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

数组 – 如何在Scala中获取Ponter / Reference语义

发布时间:2020-12-16 18:07:13 所属栏目:安全 来源:网络整理
导读:在C中,我只需要指向arr [idx]的指针(或引用). 在 Scala中,我发现自己创建了这个类来模拟指针语义. class SetTo (val arr : Array[Double],val idx : Int) { def apply (d : Double) { arr(idx) = d }} 有没有更简单的方法? Array类有没有一种方法可以返回某
在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()来读取插槽并更新(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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读