Sławosz
Sławosz

Reputation: 11687

Substitute bunch of if to pattern matching

I have following if's in scala:

myList is some List[String]

if (myList.isEmpty) return x > 5
if x < 0 return false
if (myList.head == "+") return foo()
if (myList.head == "-") return bar()

Is it possible to do it with pattern matching?

Upvotes: 1

Views: 88

Answers (3)

Petr
Petr

Reputation: 63349

It is, you can match on an empty list, and also on items inside the list. If you need just a condition without matching, use case _ if ...:

def sampleFunction: Boolean =
  lst match {
    case Nil            => x > 5
    case _ if (x < 0)   => false
    case "+" :: _       => true
    case "-" :: _       => false
    case _              => true // return something if nothing matches
  }

Upvotes: 3

om-nom-nom
om-nom-nom

Reputation: 62835

To me this one is prettier:

if(x > 0) {
  myList.headOption match {
    case Some("+") => foo()
    case Some("-") => bar()
    case None => x > 5
} else false

But I'm not sure if this doesn't confront with logical flow (e.g. early exit when list is empty -- does it break something or not in your context?), if so, feel free to say so or downvote.

Upvotes: 4

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340708

It's a bit awkward, but should work:

myList match {
  case Nil => x > 5
  case _ if x < 0 => false
  case "+" :: _ => foo()
  case "-" :: _ => bar()
}

Note that your match is not exhaustive.

Upvotes: 5

Related Questions