Q:

How to use if else expression to assign different variable name in scala

I'm trying to assign a different variable name for each value returned from the if-else expression. This is because I want to use the return value later in my program and how to use it depends on which branch (if or else) is executed.
For example:
if(5<1) {val x = 5;x} else {val y = 1; y}

current output:
res31: Int = 1

Desired output:
y: Int = 1

Thanks

A:

How about using Option to track what you computed?
scala 2.13.0-M4> val (x,y) = if (true) (Some(42), None) else (None, Some(17))
x: Option[Int] = Some(42)
y: Option[Int] = None

scala 2.13.0-M4> x.map(_ + 1).orElse(y.map(_ * 2))
res0: Option[Int] = Some(43)

scala 2.13.0-M4> val (x,y) = if (false) (Some(42), None) else (None, Some(17))
x: Option[Int] = None
y: Option[Int] = Some(17)

scala 2.13.0-M4> x.map(_ + 1).orElse(y.map(_ * 2))
res1: Option[Int] = Some(34)

