views:

437

answers:

1

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?

+2  A: 

No, this is not possible in Scala. It would probably be possible to add it to the language without compromising type soundness, but I question whether the additional complexity would be worth it.

Daniel Spiewak