14

Let's say I have a List[T] from which I need a single element, and I'd like to convert it to an Option.

val list = List(1,2,3)
list.take(1).find(_=>true) // Some(1)

val empty = List.empty
empty.take(1).find(_=>true) // None

This would appear to be somewhat of a hack ;-)

What's a better approach to converting a single element List to an Option?

dbc
  • 104,963
  • 20
  • 228
  • 340
virtualeyes
  • 11,147
  • 6
  • 56
  • 91
  • When you have doubts like that it could be useful to look at http://scalex.org/ as well. It's kind of type search for scala, similar to haskell's hoogle. You just type signature of function which you are looking for and it tries to find every function which could match. In this case just try 'List[A] => Option[A]' and you will see headOption as second result. – Piotr Kukielka Oct 31 '13 at 09:52

2 Answers2

26

Scala provides a headOption method that does exactly what you want:

scala> List(1).headOption
res0: Option[Int] = Some(1)

scala> List().headOption
res1: Option[Nothing] = None
wingedsubmariner
  • 13,350
  • 1
  • 27
  • 52
16

headOption is what you need:

scala> List.empty.headOption
res0: Option[Nothing] = None

scala> List(1,2,3).take(1).headOption
res1: Option[Int] = Some(1)
Marimuthu Madasamy
  • 13,126
  • 4
  • 30
  • 52