鉴于以下y
:
sealed trait
给定scala> sealed trait Parent
defined trait Parent
scala> case object Boy extends Parent
defined object Boy
scala> case object Girl extends Parent
defined object Girl
:
xs
我不明白这个无穷无尽的匹配警告。 scala> val xs: (Parent, (Seq[Int], Seq[Int])) = (Boy, (Nil, Nil))
xs: (Parent, (Seq[Int], Seq[Int])) = (Boy,(List(),List()))
scala> xs match {
| case (Boy, (Nil, Nil)) => 1
| case (Boy, (ys, a :: as)) => 2
| case (Boy, (ys, Nil)) => 3
| case (Girl, (Nil, Nil)) => 4
| case (Girl, (a :: as, ys)) => 5
| case (Girl, (Nil, ys)) => 6
| }
<console>:15: warning: match may not be exhaustive.
It would fail on the following inputs: (Boy, _), (Girl, _)
xs match {
^
res1: Int = 1
和(Boy, _)
的含义是什么?
我不确定(Girl, _)
除了我在右手边的比赛之外还有什么其他比赛。
答案 0 :(得分:2)
我不确定原因,但似乎Scala在使用unapply
(或apply
)时遇到了问题,因为Seq是使模式匹配成为可能的神奇之处。显然,匹配中的cons
与Seq
存在问题。如果您更改xs以使用List
,则可以使用:
val xs: (Parent, (List[Int], List[Int])) = (Boy, (Nil, Nil))
编辑:
可能您可以使用Seq
,但只需对构造进行模式匹配的方式略有不同,如下所示:
xs match {
case (Boy, (Nil, Nil)) => 1
case (Boy, (_, Seq(x, _))) => 2
case (Boy, (_, Nil)) => 3
case (Girl, (Nil, Nil)) => 4
case (Girl, (Seq(x, _), _)) => 5
case (Girl, (Nil, _)) => 6
}