Pattern matching on POJOs in Scala?
I am trying to update some of the old Scala codes for newer APIs.
In one of the libraries I am using, the case class has been converted to a simple POJO for compatibility reasons.
I was wondering if it is possible to somehow use pattern matching for a Java class.
Imagine I have a simple Java class:
public class A {
private int i;
public A(int i) {
this.i = i;
}
public int getI() {
return i;
}
}
After compilation, I would like to use it in a template, something like:
class Main extends App {
val a = ...
a match {
case _ @ A(i) =>
println(i);
}
}
For the code above I obviously get an error: Main.scala:7: error: object A is not a case class constructor, nor does it have an unapply/unapplySeq method
.
Is there a trick I could use here?
Thanks in advance!
source to share
@ som-snytt is correct, but if you're only doing it for, for example, pattern matching, then I prefer the more concise approach:
import spray.httpx.{UnsuccessfulResponseException => UrUnsuccessfulResponseException}
object UnsuccessfulResponseException {
def unapply(a: UrUnsuccessfulResponseException): Option[HttpResponse]
= Some(a.response)
}
... match {
case Failure(UnsuccessfulResponseException(r)) => r
case ...
}
Ur
is a pretentious way of saying "original", but it only accepts two letters.
source to share