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.
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!
One alternative is rather messy:
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?
If you've not come across the term before, the scope of a variable is the code it's accessible in. Variables defined within a function, if statement, or other control block are scoped to that block.
Variable scope. Java allows you to declare variables within the body of a while or if statement, but it's important to remember the following: A variable is available only from its declaration down to the end of the braces in which it is declared.
The if statement introduces a block scope by using a block statement. We say that foo is block-scoped to the if statement. This means it can only be accessed from within that block.
if is a conditional statement, which returns true or false based on the condition that is passed in it's expression. By default, if-statement is implemented on only one line, that follows it. But if we put block after the if-statement, it will be implemented on the whole block.
You can use a pattern match:
val data = 123
val (result, x) = (data*2+5.4345/2.45, data/128.4) match {
case (x, y) if x * y < 10 => (x * y, x)
case (x, _) => (x * 2, x)
}
println(x)
result
contains the result of x * y
or x * 2
, depending on which computation ran, and x
contains the value of data*2+5.4345/2.45
as desired.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With