【发布时间】:2020-07-09 23:41:23
【问题描述】:
我使用 Scala 已经有一段时间了,但它仍然让我很困扰。我不知道他们为什么把它弄得这么复杂。当这个案例类只有两个成员时,我试图理解匹配的案例类
def main(args: Array[String]): Unit = {
case class X(a: String, i: Int)
def doSome(x: X): Unit = {
x match {
case "x" X 1 => print("ahhh") // <---- HERE !
case X(_, _) => println("")
}
}
doSome(X("x", 1))
case class Y(a: String, i: Int, j: Int)
def doAnother(y:Y): Unit = {
y match {
case "y" X 1 => print("ahhh") // how to make similar syntax when there are more than one syntax ?
case Y(_, _,_) => println("") // this is understandable
}
}
doAnother(Y("y", 1,2))
}
"x" X 1 的语法如何匹配X("x",1),如果"x" X 1 可以匹配X("x",1) 那么什么匹配Y("y",1,2),显然"y" Y 1 Y 2 不起作用?
如果我们可以匹配 "y" Y (1,2),那么第一个参数有什么特别之处?
【问题讨论】:
-
case "y" Y (1,2) => ... -
@jwvh 您可以在中缀运算符中使用超过 2 个参数吗?编译器如何知道你想给它 3 个参数并且你不是要给它一个元组? (
Y("y", (1, 2))) -
这能回答你的问题吗? Scala match decomposition on infix operator