我无法正确组织来描述它的真正问题。但是这些例子我认为就足够了:
这里有一些定义类和对象,
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)
}
}
示例 1,中缀提取的正常用法与括号 at (b MatchInt c)
:
@Test
def matchOK1(): Unit = {
MatchA("abc", 123) match {
case a MatchA (b MatchInt c) =>
println(s"$a, $b, $c")
}
}
示例 2,and 中没有括号,b
但c
需要一个特殊的提取器名称定义,带有&
or:?
或?:
or+&
或+
,也许还有其他。
@Test
def matchOK2(): Unit = {
MatchA("abc", 123) match {
case a MatchA b & c =>
println(s"$a, $b, $c")
}
}
Example3,失败示例
@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
此外,错误消息非常令人困惑。
Example4,错误信息和之前类似
@Test
def matchFail2(): Unit = {
?("abc", 123) match {
case a ? b & c =>
println(s"$a, $b, $c")
}
}
提取器名称下是否有可能影响模式匹配的特殊规则?
非常感谢。