Deden Bangkit Deden Bangkit - 1 month ago 10
Scala Question

logic and if inside match case in scala

I need to use bunch of match case in scala, how do I use for or if inside the match case, so for example:

import scala.util.Random

val x = Random.nextInt(30)
val result = match x {
case 0 to 10 => bad
case 11 to 20 => average
case 20 to 30 => cool
}


first question is how do I do that instead of using
floor
,
ceil
,
round
or other math stuff?

secondly, for string value, in php we could easily use
if (x == 'some')||(x == 'thing'){result}
but how this could worked in scala match case?

for example when val x is random A to I:

val result = match x {
case A || B || C => bad
case D || E || F => average
case G || H || I => cool
}


Thanks!

Answer

Pattern matching using Guards can help you do this

val x = Random.nextInt(30)

val result = x match {
 case x if x > 0 && x <= 10 => "bad"
 case x if x > 11 &&  x <= 20 => "average"
 case x if x > 20 && x <= 30 => "cool"
 case _ => "no idea"
}

For strings you can do this

val str = "foo"

val result = str match {
 case "foo" => "found foo"
 case "bar" => "found bar"
 case _ => "found some thing"
}

Scala REPL

scala> :paste
// Entering paste mode (ctrl-D to finish)

val x = Random.nextInt(30)

val result = x match {
 case x if x > 0 && x <= 10 => "bad"
 case x if x > 11 &&  x <= 20 => "average"
 case x if x > 20 && x <= 30 => "cool"
 case _ => "no idea"
}

// Exiting paste mode, now interpreting.

x: Int = 13
result: String = average