Ade*_*lin 1 scala pattern-matching
我使用 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))
}
Run Code Online (Sandbox Code Playgroud)
语法如何"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),那么第一个参数有什么特别之处?
至少在List我看来更自然的情况下,例如考虑
List(42, 11) match {
case head :: tail =>
case Nil =>
}
Run Code Online (Sandbox Code Playgroud)
相对于
List(42, 11) match {
case ::(head, tail) =>
case Nil =>
}
Run Code Online (Sandbox Code Playgroud)
其中head :: tail直接传达 的形状List。
作为旁注,中缀表示法有时可以更清楚地传达意图,例如,考虑广义约束的语法
implicitly[List[Int] <:< Iterable[Int]] // infix type notation seems more natural
implicitly[<:<[List[Int], Iterable[Int]]]
Run Code Online (Sandbox Code Playgroud)