Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto-unboxing in Scala pattern-match

In the following code, I am getting a compilation error stating that I have a type mismatch on 'x':

val someRef: java.lang.Long = 42L
someRef match {
  case x: Long => println("The answer: " + x)
  case _ => println("Unknown")
}

How do I get Scala to auto-unbox someRef in the match statement?

like image 864
Ralph Avatar asked Oct 11 '11 16:10

Ralph


People also ask

Does Scala have pattern matching?

Pattern matching is the second most widely used feature of Scala, after function values and closures. Scala provides great support for pattern matching, in processing the messages. A pattern match includes a sequence of alternatives, each starting with the keyword case.

How does Scala pattern matching work?

Pattern matching is a mechanism for checking a value against a pattern. A successful match can also deconstruct a value into its constituent parts. It is a more powerful version of the switch statement in Java and it can likewise be used in place of a series of if/else statements.

What is case _ in Scala?

case _ => does not check for the type, so it would match anything (similar to default in Java). case _ : ByteType matches only an instance of ByteType . It is the same like case x : ByteType , just without binding the casted matched object to a name x .

What is pattern matching explain with example?

Pattern matching is the process of checking whether a specific sequence of characters/tokens/data exists among the given data. Regular programming languages make use of regular expressions (regex) for pattern matching.


1 Answers

The type system doesn't know about boxing at this level. But it does know that if there is an Any, a boxed Long is really (presumably) supposed to be just a Long (from the AnyVal part of the class inheritance tree). So:

val someRef: java.lang.Long = 42L
(someRef: Any) match {
  case x : Long => println("The answer is " + x)
  case _ => println("What answer?")
}
like image 118
Rex Kerr Avatar answered Sep 29 '22 01:09

Rex Kerr