Why does a scala try block allow variables from the enclosing scope to be redefined?

和自甴很熟 提交于 2019-12-11 10:29:13

问题


Using Scala 2.10, the following compiles without an error.

val test = 1
try {
  val test = 2
}

Looking at the byte code generated, I see this:

int test = 1;
int test = 2;

Isn't this strange? Or am I missing something obvious?


回答1:


This has nothing to do with try. Variables can shadow each other in any block, and you can put blocks basically anywhere:

val x = 0
if ({val x = 1; x*3}==0) {
  val x = 2; x + x + x
}
else x

This makes code more portable: you can freely move blocks around without worrying that something on the outside might conflict. (Well, not entirely true: which implicits are in scope can still cause problems, but that's much less likely to trip you up than duplicated variables.)

It is a different choice from Java; Java's attitude is that you're more likely to forget your variable names and need to be reminded, while Scala's is that you probably mean what you say even if the outside context changes. This sort of makes sense given Java's focus on mutable operations (shadowing a mutable variable can really cause problems!) and Scala's on immutable-by-default (shadowing the outer immutable variable is probably even desirable since you can reuse short variables like i and x to your heart's content).




回答2:


A local variable can always have the same name as one with wider scope. By declaring it inside your braces you effectively protect yourself from accidentally using/overwriting a variable used elsewhere . Not strange - but useful!




回答3:


Perhaps you try this to get a clear picture of whats going on

val test = 1
println(test)
try{
  val test = 2
  println(test)
}
println(test)

The scope matters. I expect you got 1 2 1 The second test only exists within the try scope



来源:https://stackoverflow.com/questions/14979813/why-does-a-scala-try-block-allow-variables-from-the-enclosing-scope-to-be-redefi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!