简体   繁体   中英

Pattern matching on POJOs in Scala?

I'm trying to update some of my old Scala code to new APIs.

In one of the libraries I use, a case class has been converted to a simple POJO for compatibility reasons.

I was wondering if it is still possible somehow to use pattern matching for the Java class.

Imagine I have a simple Java class like:

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 pattern matching somehow 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 any trick I could use here?

Thanks in advance!

It's a little late in the 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
    }
  }
}

Write unapply yourself:

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

@som-snytt's answer is correct - but if you are doing this just for eg pattern-matching then I prefer the more succinct 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 takes two letters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM