Question

Given a list, what is the best way to return a value depending on the empty-ness of that list?

Using match?

xs match {
    case Nil => a
    case _ => b
}

Or an if statement?

if (xs.isEmpty) a else b

It seems that pattern matching triggered a lot of a boilerplate in this case. Is there an idiomatic solution for this case?

Was it helpful?

Solution

"Preference" is subjective, but the simple if has a few advantages:

  • there doesn't seem to be a need to use pattern matching in this case, since you're not really exploiting its functionality (no extraction for example).

  • the second approach tells you explicitly that you check whether the list is empty, and hence is immediately readable.

In summary: pattern matching in Scala is a powerful tool, and because of its power it adds complexity to your code, both in terms of machine- and human-readability. In other words: not everything is a nail ;).

OTHER TIPS

The pattern match syntax is preferred when you need recursion or head :: tail. List in Scala is inspired by older ML languages(Cons(head, tail)) and you get a nice head :: tail pair to match:

someList match {
   case head :: tail => // this will actually be someList.head and someList.tail
   case Nil => // ..
}

I wouldn't say it's nicer, but an alternative is:

 xs.headOption.fold(a)(_ => b)

In this case, it looks a little bit weird because you're ignoring the head element and returning b instead, but if you actually wanted to use it as return value, the following is quite elegant:

xs.headOption.getOrElse(a)   //will return the head element or a if none

My favourite would be adding some scalaz:

import scalaz._
import Scalaz._


xs.headOption ? b |  a    // if defined 'b' else 'a'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top