Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala pattern matching referencing

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.

like image 401
user1553248 Avatar asked May 24 '26 13:05

user1553248


2 Answers

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.

like image 120
Jatin Avatar answered May 26 '26 08:05

Jatin


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

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

like image 36
dhg Avatar answered May 26 '26 07:05

dhg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!