我无法正确组织来描述真实的问题。但是那些例子我觉得这已经足够了:
这里有一些定义类和对象,
case class ?(a: String, b: Int)
case class MatchA(a: String, b: Int)
object MatchInt {// can't
def unapply(arg: Int): Option[(Long, Double)] = {
Some(arg, arg)
}
}
object & {// or :? or ?: or +& or +
def unapply(arg: Int): Option[(Long, Double)] = {
Some(arg, arg)
}
}
(b MatchInt c)
: @Test
def matchOK1(): Unit = {
MatchA("abc", 123) match {
case a MatchA (b MatchInt c) =>
println(s"$a, $b, $c")
}
}
b
和c
中没有括号,但需要&
或:?
或?:
或+&
的特殊提取名称定义或+
,也许是其他人。 @Test
def matchOK2(): Unit = {
MatchA("abc", 123) match {
case a MatchA b & c =>
println(s"$a, $b, $c")
}
}
@Test
def matchFail1(): Unit = {
MatchA("abc", 123) match {
case a MatchA b MatchInt c =>
println(s"$a, $b, $c")
}
}
发生了两个错误:
pattern type is incompatible with expected type;
[error] found : Int
[error] required: Match.this.MatchA
[error] case a MatchA b MatchInt c =>
[error] ^
和
constructor cannot be instantiated to expected type;
[error] found : Match.this.MatchA
[error] required: Long
[error] case a MatchA b MatchInt c =>
[error] ^
[error] two errors found
此外,错误信息非常混乱。
@Test
def matchFail2(): Unit = {
?("abc", 123) match {
case a ? b & c =>
println(s"$a, $b, $c")
}
}
提取器名称下是否有特殊规则可以影响模式匹配?
非常感谢。
答案 0 :(得分:0)
模式表达式的解析与普通表达式相同。
(在模式之外,你得到apply
,在模式中,你得到unapply
。)
关联性和优先级的规则是in the spec。
运算符的优先级高于alnum标识符。
这就是为什么你的示例2有效,但我想你不喜欢这种语法。