Scala 模式匹配引用

标签 scala pattern-matching

当模式匹配案例类时,您实际上如何引用它所匹配的类?

这是一个例子来说明我的意思:

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/

相关文章:

scala - 如何按顺序执行scala future list

c# - 模式匹配优先于引用还是值相等?

java - 如何替换: [text](link) with <a href ="link">text</a> in java?

java - 解析特定的文本文件java

scala - 无法保持Scala应用程序在docker上运行

scala - 在 Scala 中只坚持函数范式的功效

scala - 迭代日期范围(scala 方式)

scala - 为什么 Scala 的 BigDecimal 没有零?

regex - 如何使用正则表达式匹配字符串中的前一个字符

arrays - Scala 中的多重赋值而不使用数组?