Scala generics type inference for Java classes

Viewed 57

Suppose we have following Java interface defined in some external library (so we have no control over it):

public interface JavaTest<R extends Something> { }

public class JavaTestImpl implements JavaTest<SomethingSpecific> {
  public static final JavaTestImpl INSTANCE = ...
}

Now we want to write Scala function which will take arbitrary instance of JavaTest as argument and extract both type of instance itself and R generic argument (e.g. we want to do implicit typeclass lookup on instance class):

def test[A <: Something, X <: JavaTest[A]](x: X)(implicit tc: TypeClass[X]): A = {}

test(JavaTestImpl.INSTANCE) // should be [SomethingSpecific, JavaTestImpl]

unfortunately, it does not work straightforward way: compiler infers test invocation as [Nothing, JavaTestImpl] and then immediately fails because inferred types are wrong and don't satisfy the constraints.

Is there a way to make Scala compiler infer corresponding type arguments without changing Java part and without writing a lot of boilerplate every time? Or, to put question another way, is there a way to extract generic type (SomethingSpecific) given that we know type of instance (JavaTestImpl)?

0 Answers
Related