Saqib Ali Saqib Ali - 2 months ago 12
Scala Question

If then else in a map

What is a more concise way of representing the following If then else:

val result = scores.map(score =>
if (score == 0)
("retake", 1)
else if (score < 0)
("fail", 1)
else
("pass", 1)
)

Answer

Pattern matching with guards

scores map {
  case 0 => "retake" -> 1
  case x if x < 0 => "fail" -> 1
  case _ => "pass" -> 1
}
Comments