Auto-unboxing in Scala pattern-match
Asked Answered
D

1

6

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?

Disuse answered 11/10, 2011 at 16:27 Comment(0)
W
12

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?")
}
Wallachia answered 11/10, 2011 at 16:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.