为什么 scala try 块允许重新定义封闭作用域中的变量? [英] Why does a scala try block allow variables from the enclosing scope to be redefined?

查看:45
本文介绍了为什么 scala try 块允许重新定义封闭作用域中的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Scala 2.10,以下编译没有错误.

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?

推荐答案

这与 try 无关.变量可以在 any 块中相互遮蔽,基本上你可以把块放在任何地方:

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

与Java不同的选择;Java 的态度是你更有可能忘记你的变量名并需要被提醒,而 Scala 的态度是即使外部上下文发生变化,你也可能是你所说的.鉴于 Java 专注于可变操作(隐藏可变变量确实会导致问题!)和 Scala 的默认不可变(隐藏外部不可变变量甚至可能是可取的,因为您可以重用像 i 和 x 这样的短变量,这种情况是有道理的尽情享受吧).

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

这篇关于为什么 scala try 块允许重新定义封闭作用域中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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