Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If-statement scoped variables

Tags:

scala

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?

like image 680
vertexshader Avatar asked Jan 13 '12 03:01

vertexshader


People also ask

Are IF statements scoped?

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.

Can you declare variables in an if statement?

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.

Are IF statements scoped Javascript?

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.

What is the default scope of IF statement?

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.


1 Answers

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.

like image 53
earldouglas Avatar answered Sep 30 '22 17:09

earldouglas