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") => ... }

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

@JRR in that case regex is better idea instead of OR. see the updated example. you would basically need hi.*|hello.* regex

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.