Variables with if-statement variables

Often I have a desire to create variables that are bound to an if statement. Some calculations refer only to a certain statement β€œif” - it smells bad for contamination of the external area with temporary variables.

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 of the options is pretty 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 explicit alternative I'm trying to avoid is:

 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 this possible in Scala? Is there a decent solution? If not, what other languages ​​support this idea?

+8
scala
source share
3 answers

Since if in Scala is an expression, that is, it returns a value, usually you set some value to the result of the if expression. So your third alternative is just fine: put it in a block of code, 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 } 

None of the declared in the val block is available.

+20
source share

You can use pattern matching:

 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 x * y or x * 2 , depending on what calculation was performed, and x contains the value data*2+5.4345/2.45 as desired.

+5
source share

You can create an area for it ...

 { val x = data*2+5.4345/2.45 val y = data/128.4; if ( x*y < 10) x * y else x * 2 } 

Or, to make it understandable,

 locally { val x = data*2+5.4345/2.45 val y = data/128.4; if ( x*y < 10) x * y else x * 2 } 
0
source share

All Articles