Search code examples
scalafunctional-programming

In Scala, how to define a `val` in a `if block`?


My Scala codes looks like this

if (true) {
  val a = 1
}
else {
  val a = 2
}

print(a)
print(a+100)

the print(a) will throw an error because a is out of scope when evaluating that line.. Then how can I define a val according to a conditional expression? Does anyone have ideas about this?


Solution

  • In scala if is expression - it returns value. So you could assign this value to val:

    val a =
      if (true) {
        1
      } else {
        2
      }
    
    // for simple expressions:
    val a2 = if (true) 1 else 2
    
    print(a)
    print(a+100)
    

    It's good to note that this idiom can also be extended to declaring and setting multiple variables by taking advantage of destructuring assignment:

    val (a, b) =
      if (true) {
        (1, 5)
      } else {
        (2, 10)
      }
    
    print(a)
    print(b)
    

    The above can further be extended to match statements and unpacking anything that can be unapply'd.

    Additionally, if you have multiple variables of the same type, you can use list deconstruction:

    val List(a, b) =
      if (true)
        List(1, 5)
      else
        List(2, 10)
    
    // OR
    
    val a :: b :: Nil =
      if (true)
        List(1, 5)
      else
        List(2, 10)
    
    print(a)
    print(b)
    

    See also Programming in Scala/Built-in Control Structures