Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 正在检索选项[列表[…]的标题]_Scala - Fatal编程技术网

Scala 正在检索选项[列表[…]的标题]

Scala 正在检索选项[列表[…]的标题],scala,Scala,给定一个Some(List(“hello”)并想要得到“hello”,我观察到以下行为 scala> val list = Some(List("hello")) list: Some[List[String]] = Some(List(hello)) scala> list.head.head res3: String = hello 然后,我检查了,并看到head将选择此iterable集合的第一个元素。它还指出,如果集合为空,将抛出异常 对选项[List]的第一个元素的检索

给定一个
Some(List(“hello”)
并想要得到
“hello”
,我观察到以下行为

scala> val list = Some(List("hello"))
list: Some[List[String]] = Some(List(hello))

scala> list.head.head
res3: String = hello
然后,我检查了,并看到
head
选择此iterable集合的第一个元素。
它还指出,如果集合为空,将抛出异常

对选项[List]的第一个元素的检索被认为是惯用的吗?

它不是惯用的,但我倾向于:

scala> val hd = list.flatMap(_.headOption)
hd: Option[String] = Some(hello)

然后继续使用选项值。

答案实际上取决于您下一步如何使用该值。例如,您可以使用@Shadowlands建议的内容,并使用
map
flatMap
继续使用
选项。您可以做的另一件事是使用模式匹配:

list match {
  case Some(head :: tail) => soSomethingWith(head)
  case Some(Nil) => dealWithEmptyList
  case None => dealWithNone
}

你是说这个表达法不地道
Some
是Scala处理空值可能性的一种方法。人们可以把
Some
的概念解释为一个只有头没有尾的列表,但只是一个隐喻,而不是惯用用法。您真正要表达的是一个嵌套列表:

val list: List[List[String]] = List(List("hello"))
但是,如果您100%确定
list
有一个值,它是非空列表,那么我会这样做:

list match { case Some(xs) => xs.head }

如果你这么想的话,你也可以用一种理解的方法来达到目的。我可能更喜欢@Shadowlands answer,因为它更简洁,但这同样适用:

val headOpt = 
  for{
    list <- listOpt
    head <- list.headOption
  } yield head 
val headOpt=
为了{
列表