Scala 模式匹配引用 [英] Scala pattern matching referencing

查看:55
本文介绍了Scala 模式匹配引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When pattern matching case classes how do you actually refer to the class which it was matched to?

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

Here's an example to show what I mean:

sealed trait Value
case class A(n: Int) extends Value

v match {
  case A(x) =>
   doSomething(A);
}

其中 v 是 value 类型,doSomething 接受 A 类型的参数,而不是 Value.

Where v is of type value and doSomething takes an parameter of type A, not Value.

推荐答案

这样做

v match {
   case a @ A(x) =>
   doSomething(a)
}

@ 被称为 Pattern Binder(参见第 8.1 节.3).来自参考:

@ is called Pattern Binder (Refer § 8.1.3). From the reference:

模式绑定器 x@p 由模式变量 x 和模式 p 组成.变量 x 的类型是模式 p 的静态类型 T.这模式匹配任何与模式 p 匹配的值 v,前提是v 的运行时类型也是 T 的一个实例,它绑定了该值的变量名称.

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 模式匹配引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆