如何使用模式匹配检查列表是否包含所有Some或None或两者?

Fre*_*ind 1 scala pattern-matching

有一个类型列表List[Option[String]],它可能包含SomeNone

val list:List[Option[String]] = List(Some("aaa"), None, Some("bbb"))
list match {
   case /*List with all Some*/ => println("all items are Some")
   case /*List with all None*/ => println("all items are None")
   case /*List with Some and None*/ => println("Contain both Some and None")
}
Run Code Online (Sandbox Code Playgroud)

但我不知道如何写它.是否可以使用模式匹配?

win*_*ner 8

您可以编写自定义提取器:

object AllSome {
  def unapply[T](l: List[Option[T]]) = l.forall(_.isDefined)
}

object AllNone {
  def unapply[T](l: List[Option[T]]) = l.forall(_ == None)
}

object Mixed {
  def unapply[T](l: List[Option[T]]) = !AllNone.unapply(l) && !AllSome.unapply(l)
}
Run Code Online (Sandbox Code Playgroud)

并使用它们像:

list match {
  case AllSome() => ???
  case AllNone() => ???
  case Mixed() => ???
}
Run Code Online (Sandbox Code Playgroud)