我往往想在发言时产生范围很广的变量。 有些计算仅与某一具体数据有关,如果说的话——用临时变数 bad坏对外部范围进行污染。
What I would like to do:
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
Is something like this possible in Scala? Is there a decent workaround? If not, what other languages support an idea like this?