Fre*_*ind 1 scala pattern-matching
有一个类型列表List[Option[String]],它可能包含Some或None
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)
但我不知道如何写它.是否可以使用模式匹配?
您可以编写自定义提取器:
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)
| 归档时间: |
|
| 查看次数: |
2552 次 |
| 最近记录: |