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?
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With