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?
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.
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.
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 .
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.
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?")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With