Compact syntax for getting list header as an option

Is there a compact way to get the list title as Some when the list is not empty, and None otherwise?

This is what I'm doing right now

val ms = moves.filter { ...some predicate... }
if (ms.nonEmpty) Some(ms.head) else None
+5
source share
2 answers

Give it a try headOption. API documents are your friend.

Note that it findperforms exactly filterplus headOption: it takes one element, if any, and puts it in an option, and otherwise gives None.

+18
source

, , , ( Scalaz)

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

:

if (condition) Some(result) else None

:

condition option result
+1

All Articles