Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional variable setting

I need to set a variable depending on a condition. But since variables are immutable, I find myself in a sticky situation having to repeat code. What I'd like to do is:

def doSomething(x:Int):Int = {
  if(x==1){
    val player="Andy"
  } else {
    val player="Rob"
  }
  getSomeValue(player) // Another function
}

But the variable "player" is no longer in scope. Only way I see is to call the function "getSomeValue" in both the condition blocks, but that's not something I'd like to do. How do I get around this using immutable variables?

like image 229
Plasty Grove Avatar asked Nov 19 '12 14:11

Plasty Grove


People also ask

How do you set a variable based on a condition?

var a = 1; var b = a > 0? (a === 1? "A is 1" : "A is not 1") : (a === 0? "A is zero" : "A is negative"); Method 2: In this method, if the value of the left of the || is equal to zero, false, null, undefined, or an empty string, then the value on the right will be assigned to the variable.

What is conditional variable?

Condition variables are synchronization primitives that enable threads to wait until a particular condition occurs. Condition variables are user-mode objects that cannot be shared across processes. Condition variables enable threads to atomically release a lock and enter the sleeping state.


1 Answers

def doSomething(x:Int):Int = {
  val player = if(x==1){
    "Andy"
  } else {
    "Rob"
  }
  getSomeValue(player)
}
like image 103
Robin Green Avatar answered Nov 15 '22 23:11

Robin Green