문제

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?

도움이 되었습니까?

해결책

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?")
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top