问题描述
我经常希望创建作用域为 if 语句的变量.一些计算只与特定的if"语句相关 - 用临时变量来污染外部作用域.
Often times I have a desire to create variables scoped to an if statement. Some computations only relate to a particular 'if' statement - to pollute the outer scope with temporary variables smells bad.
我想做什么:
val data = (whatever)
if (val x = data*2+5.4345/2.45; val y = data/128.4; x*y < 10)
x * y
else
x * 2
println(x) //ERROR!
另一种选择相当混乱:
val data = (whatever)
if (data*2+5.4345/2.45*data/128.4 < 10)
data*2+5.4345/2.45*data/128.4
else
data*2+5.4345/2.45 * 2
我试图避免的明显替代方案:
The obvious alternative I'm trying to avoid:
val data = (whatever)
val x = data*2+5.4345/2.45
val y = data/128.4
if (x*y < 10)
x*y
else
x * 2
println(x) //OK
在 Scala 中可以实现这样的功能吗?有体面的解决方法吗?如果没有,还有哪些其他语言支持这样的想法?
Is something like this possible in Scala? Is there a decent workaround? If not, what other languages support an idea like this?
推荐答案
因为 if
在 Scala 中是一个表达式,即它返回一个值,通常你会为结果设置一些值你的 if
表达式.所以你的第三个选择很好:把它放在一个代码块中,即
Since if
in Scala is an expression, i.e. it returns a value, normally you'd be setting some value to the result of your if
expression. So your third alternative is just fine: put it in a code block, i.e.
val data = (whatever)
val myValue = {
val x = data*2+5.4345/2.45
val y = data/128.4
if (x*y < 10)
x*y
else
x * 2
}
在块内声明的 val
在块外都不可用.
None of the val
s declared within the block are available outside it.
这篇关于If 语句作用域变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!