当模式匹配案例类时,您实际上如何引用它所匹配的类?
这是一个例子来说明我的意思:
sealed trait Value
case class A(n: Int) extends Value
v match {
case A(x) =>
doSomething(A);
}
哪里
v
是 value 类型和 doSomething
接受类型为 A
的参数,不是 Value
.
最佳答案
做这个
v match {
case a @ A(x) =>
doSomething(a)
}
@
被称为 Pattern Binder (参见第 8.1.3 节)。从引用:A pattern binder x@p consists of a pattern variable x and a pattern p. The type of the variable x is the static type T of the pattern p. This pattern matches any value v matched by the pattern p, provided the run-time type of v is also an instance of T , and it binds the variable name to that value.
关于Scala 模式匹配引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21521637/