加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala模式匹配引用

发布时间:2020-12-16 10:06:25 所属栏目:安全 来源:网络整理
导读:当模式匹配案例类时,你如何实际引用它匹配的类? 这是一个展示我的意思的例子: sealed trait Valuecase class A(n: Int) extends Valuev match { case A(x) = doSomething(A);} 其中v是类型值,doSomething采用类型A的参数,而不是值. 解决方法 做这个 v matc
当模式匹配案例类时,你如何实际引用它匹配的类?

这是一个展示我的意思的例子:

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

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

其中v是类型值,doSomething采用类型A的参数,而不是值.

解决方法

做这个

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读