Scala pattern matching referencing

泄露秘密 提交于 2019-12-07 18:45:41

问题


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);
}

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


回答1:


Do this

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

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

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.




回答2:


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

By the way, you don't need the semicolon.




回答3:


Case classes are deconstructed

You wouldn't refer to A, as you would refer to the deconstructed object, hence you would only get access to x in the context of your case.

However, you would know that the context was A, since you matched the case, so it would be easy to construct a new case class from your arguments.



来源:https://stackoverflow.com/questions/21521637/scala-pattern-matching-referencing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!