0

I'm using value class in Scala to avoid boxing at runtime.

Eg.:

trait Service {
  def getThing(thingId: ThingId): Thing
}

final case class ThingId(value: Long) extends AnyVal

However, I'm using that same value class from Java code:

interface JavaService {
    Thing getThing(ThingId thingId);
}

This does not work since ThingId is actually compiled as a Long:

JavaService.java:[2,19] error: 
  incompatible types: ThingId cannot be converted to long

Is there a pattern to use value classes (or any wrapper/helper that would help) from Java?

Alban Dericbourg
  • 1,616
  • 2
  • 16
  • 39
  • The initial question was not (this one is a "how" and the other one is a "why")... the the comments of the other one actually seem to answer that question: there is no elegant pattern. – Alban Dericbourg Jan 16 '17 at 12:19
  • Indeed, there is no elegant way to do this since this is an optimization in Scala land. All the JVM sees is the underlying type (hopefully, if you follow the `AnyVal` pattern correctly). – Yuval Itzchakov Jan 16 '17 at 12:23

0 Answers0