You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala中for循环迭代时Point的y值逐次递增1的原因咨询

Scala代码中Point数组更新逻辑解析

首先贴出对应的Scala代码:

case class Point(x: Int, y: Int){   
  def +(rhs : Point) : Point = Point(x + rhs.x, y + rhs.y)    
}

object ArrayTest {    
  def main(args : Array[String]) : Unit = {    
    val a : Array[Point] = new Array(5)    
    val p : Point = Point(6, -4)    
    for(i <- a.indices) a(i) = p    
    for(i <- a.indices) a(i) += Point(2, i)    
    var sum = 0    
    for(p <- a) sum += p.y    
    print(sum)   
  }    
}

核心逻辑拆解

  1. Point类的+方法:实现两个Point对象的分量相加——把两个Point的x、y值分别相加,返回新的Point对象(case class默认不可变,不会修改原对象)。

  2. 第一个for循环的作用:把数组a的5个元素全部指向同一个Point实例p(6, -4)。

  3. 第二个for循环的关键逻辑:

    • a.indices对应数组索引范围0到4,循环变量i会依次取0、1、2、3、4;
    • 每次循环执行的a(i) += Point(2, i)等价于a(i) = a(i) + Point(2, i);
    • 计算细节:
      • x值:原Point的x是6,加上新Point的x=2,结果始终为8;
      • y值:原Point的y是-4,加上新Point的y=i(i从0到4递增),所以y的结果依次是-4+0=-4、-4+1=-3、-4+2=-2、-4+3=-1、-4+4=0;
    • 每次生成的新Point会重新赋值给a(i),这就是数组元素y值逐次加1的原因。

简单来说:y值逐次加1是因为循环索引i每次递增1,而每次相加的Point的y分量就是当前的i,和原Point的y(-4)相加后,结果自然跟着i递增。逻辑触发点就是第二个for循环里的Point(2, i),这里的i是循环的动态索引值。

内容的提问来源于stack exchange,提问作者IGG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 16:35:29