1

Can I combine the following two cases into one case clause since they both do the same thing?

e match {
  case "hello" => e + "world"
  case "hi" => e + "world
}

Also, what about if I want to match using startsWith e.g.,

e match { case e.startsWith("he") | e.startsWith("hi") => ... }
JRR
  • 6,014
  • 6
  • 39
  • 59

1 Answers1

3

Yes you can simply use or (|) to match one of the pattern,

scala> "hi" match { case "hello" | "hi" => println("fantastic")  case _ => println("very very bad")}
fantastic

scala> "hello" match { case "hello" | "hi" => println("fantastic")  case _ => println("very very bad")}
fantastic

scala> "something else" match { case "hello" | "hi" => println("fantastic")  case _ => println("very very bad")}
very very bad

You can also use regex to pattern match, especially useful when there are many criterias to match,

scala> val startsWithHiOrHello = """hello.*|hi.*""".r
startsWithHiOrHello: scala.util.matching.Regex = hello.*|hi.*

scala> "hi there" match { case startsWithHiOrHello() => println("fantastic")  case _ => println("very very bad")}
fantastic

scala> "hello there" match { case startsWithHiOrHello() => println("fantastic")  case _ => println("very very bad")}
fantastic

scala> "non of hi or hello there" match { case startsWithHiOrHello() => println("fantastic")  case _ => println("very very bad")}
very very bad

Refer to Scala multiple type pattern matching and Scala match case on regex directly

prayagupa
  • 30,204
  • 14
  • 155
  • 192
  • @JRR in that case regex is better idea instead of `OR`. see the updated example. you would basically need `hi.*|hello.*` regex – prayagupa Jun 05 '17 at 23:10