Scala unapplySeq 提取器语法
Scala unapplySeq extractor syntax
我(无意中)遇到了一些模式匹配语法,我没想到会编译,但现在无法理解。
它似乎与 unapplySeq
有关。
注意这个简单示例中的 case x List(_,_)
部分:
val xs = List(1, 2, 3) //> xs : List[Int] = List(1, 2, 3)
xs match {
case x List (_, _) => "yes"
case _ => "no"
} //> res0: String = yes
我习惯了模式匹配语法中的:
或@
,但对此感到困惑。这个语法是如何工作的,它与 unapplySeq
?
的关系是什么(如果有的话)
在 Scala 2.11.6 中执行的示例代码
等效的非中缀版本是:
xs match {
case List(x, _, _) => "yes"
case _ => "no"
}
An infix operation pattern p;op;q is a shorthand for the constructor
or extractor pattern op(p,q). The precedence and associativity of
operators in patterns is the same as in expressions.
An infix operation pattern p;op;(q1,…,qn) is a shorthand for the
constructor or extractor pattern op(p,q1,…,qn).
我(无意中)遇到了一些模式匹配语法,我没想到会编译,但现在无法理解。
它似乎与 unapplySeq
有关。
注意这个简单示例中的 case x List(_,_)
部分:
val xs = List(1, 2, 3) //> xs : List[Int] = List(1, 2, 3)
xs match {
case x List (_, _) => "yes"
case _ => "no"
} //> res0: String = yes
我习惯了模式匹配语法中的:
或@
,但对此感到困惑。这个语法是如何工作的,它与 unapplySeq
?
在 Scala 2.11.6 中执行的示例代码
等效的非中缀版本是:
xs match {
case List(x, _, _) => "yes"
case _ => "no"
}
An infix operation pattern p;op;q is a shorthand for the constructor or extractor pattern op(p,q). The precedence and associativity of operators in patterns is the same as in expressions.
An infix operation pattern p;op;(q1,…,qn) is a shorthand for the constructor or extractor pattern op(p,q1,…,qn).