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!

+3


source to share


3 answers


A bit late at night here for subtlety, but



object `package` {
  val A = AX
}

object AX {
  def unapply(a: A): Option[Int] = Some(a.getI)
}

object Test extends App {
  Console println {
    new A(42) match {
      case A(i) => i
    }
  }
}

      

+2


source


Write unapply

yourself:



object A {
    def unapply(x: A) = Some(x.getI)
}

      

+1


source


Answer to

@ 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.

+1


source







All Articles