6

Is there a compact way to get the head of a list as a Some when the list is non-empty, getting None otherwise?

This is what I am currently doing,

val ms = moves.filter { ...some predicate... }
if (ms.nonEmpty) Some(ms.head) else None
giampaolo
  • 6,906
  • 5
  • 45
  • 73
Janek Bogucki
  • 5,033
  • 3
  • 30
  • 40

2 Answers2

22

Try headOption. The API docs are your friend.

Note also that find does exactly a filter plus headOption: it takes one item if there and puts it in an option, and otherwise gives None.

M. Justin
  • 14,487
  • 7
  • 91
  • 130
Rex Kerr
  • 166,841
  • 26
  • 322
  • 407
1

The answer above is correct for this case, but where you just need to simplify the second line, I also recommend this handy utility mentioned here (adopted from Scalaz):

implicit class boolean2Option(val value: Boolean) extends AnyVal {
  def option[A](f: => A) = if (value) Some(f) else None
}

Allows this:

if (condition) Some(result) else None

to become this:

condition option result
Community
  • 1
  • 1
Tim
  • 1,615
  • 14
  • 17