Scala高级循环 [英] Scala advanced loop

查看:65
本文介绍了Scala高级循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  var z = 10
  for (i <- 1 to 3; x = i + 1; y = z - 1) {
    println(x)
    println(y)
    z -= 1
  }

输出:

2 9 3 9 4 9

2 9 3 9 4 9

这不是我所期望的.似乎for循环总是保持z =10.有人可以帮我解释一下吗?

It is not what I expect. It seems the for loop always keeps z = 10. Can someone help me explain this?

推荐答案

您可以按照以下步骤检查正在运行的内容:

You can inspect what you are running as following:

scala> import scala.reflect.runtime.{universe => ru}
scala> import ru._
scala> q"""for (i <- 1 to 3; x = i + 1; y = z - 1) {
     |     println(x)
     |     println(y)
     |     z -= 1
     |   }
     | """
res13: reflect.runtime.universe.Tree =
1.to(3).map(((i) => {
  val x = i.$plus(1);
  val y = z.$minus(1);
  scala.Tuple3(i, x, y)
})).foreach(((x$1) => x$1: @scala.unchecked match {
  case scala.Tuple3((i @ _), (x @ _), (y @ _)) => {
    println(x);
    println(y);
    z.$minus$eq(1)
  }
}))

如果您看到扩展的代码,我相信足以说服您y应该始终为9.

If you see the expanded code, I believe it should be enough to convince you that y should always be 9.

这篇关于Scala高级循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆