error in if return in Scala

if(a>4) {
  val result = a
}

this is creating a second val named result that is only scoped (visible) inside the if block, so the return statement always returns the value defined on line 2.

A val can not be reassigned so you would need to use a var if you needed to change the value:

var result = 3
if (a > 4) {
  // no `var` or `val` prefix indicates we are
  // referring to an existing variable that's already declared
  result = a
}

but for a simple case like this you can avoid the variable and use:

def vertify(a: Int): Int = if (a > 4) a else 3

Leave a Comment