[英]Understanding pattern matching on lists
我最近一直在玩提取器,並且想知道List提取器如何工作尤其如此:
List(1, 2, 3) match {
case x :: y :: z :: Nil => x + y + z // case ::(x, ::(y, ::(z , Nil)))
}
Ok ::用在模式中,所以我猜編譯器現在在:: - Object中查找unapply方法。 試過這個:
scala> (::).unapply(::(1, ::(2, Nil)))
res3: Option[(Int, List[Int])] = Some((1,List(2)))
很好,有效。 但是,這不是:
scala> (::).unapply(List(1,2,3))
<console>:6: error: type mismatch;
found : List[Int]
required: scala.collection.immutable.::[?]
(::).unapply(List(1,2,3))
這樣做:
scala> List.unapplySeq(List(1,2,3))
res5: Some[List[Int]] = Some(List(1, 2, 3))
其實我此刻有點困惑。 編譯器如何在此處選擇正確的unapply實現。
匹配基本上是做以下事情:
(::).unapply(List[Int](1,2,3).asInstanceOf[::[Int]])
一旦它知道它是安全的(因為List(1,2,3).isInstanceOf[::[Int]]
為true
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.