将1个元素的列表转换为Option

vir*_*yes 13 collections scala converter option

假设我有一个List [T],我需要一个元素,我想把它转换成一个Option.

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

val empty = List.empty
empty.take(1).find(_=>true) // None
Run Code Online (Sandbox Code Playgroud)

这看起来有点像黑客;-)

将单个元素列表转换为选项的更好方法是什么?

win*_*ner 26

Scala提供了headOption一种完全符合您要求的方法:

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

scala> List().headOption
res1: Option[Nothing] = None
Run Code Online (Sandbox Code Playgroud)


Mar*_*amy 16

headOption 是你需要的:

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

scala> List(1,2,3).take(1).headOption
res1: Option[Int] = Some(1)
Run Code Online (Sandbox Code Playgroud)