Search code examples
scalacollectionsconvertersscala-option

Convert List of 1 element to Option


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?


Solution

  • 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