Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

227
Views
Scala generics type inference for Java classes

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)?

over 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!