Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 763
virtualeyes Avatar asked Oct 30 '13 18:10

virtualeyes


2 Answers

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
like image 120
wingedsubmariner Avatar answered Nov 03 '22 12:11

wingedsubmariner


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)
like image 28
Marimuthu Madasamy Avatar answered Nov 03 '22 13:11

Marimuthu Madasamy