zakvdm
zakvdm

Reputation: 489

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

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?

Upvotes: 1

Views: 578

Answers (3)

Rex Kerr
Rex Kerr

Reputation: 167931

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).

Upvotes: 2

korefn
korefn

Reputation: 955

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

Upvotes: 2

Floris
Floris

Reputation: 46445

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!

Upvotes: 3

Related Questions