I'm using Scala implicits to define a rich wrapper for a Java interface:
class RichThing { def richStuff: Unit = {} }
In the companion object I define the implicit conversion and an apply
factory method:
object RichThing {
implicit def rich( thing: JavaThing ) = new RichThing()
def apply() = new RichThing()
}
With this, I can instantiate a Java implementation of the interface and use it like a RichThing
(due to the implicit conversion):
new JavaThingImpl().richStuff
I can also create a RichThing
using the factory method (due to the apply
method):
val a = RichThing()
What I'd like to do is instantiate arbitrary Java implementations of the interface in the same way. This doesn't work, as Scala then looks for a companion object of the implementation and can't find one:
val b = JavaThingImpl() // "not found: value JavaThingImpl"
I could create a Scala companion object for the Java implementation:
object JavaThingImpl { def apply() = new RichThing() }
But the point would be to make this work for any (in particular unknown) implementation of the interface.
Is there any way to realize this? For instance, to create Scala companion objects for the Java implementations on the fly, based on the implicit conversion in the RichThing
object?
Or to create the Scala companion object from the Java side, maybe in an abstract class?