Home > Software engineering >  Incompatible types trying to return class implementing parameterized interface
Incompatible types trying to return class implementing parameterized interface

Time:03-25

I have defined this class:

public class ActorMapper implements RecordMapper<ActorRecord, ActorModel>

Elsewhere, in a function with this signature:

public <R extends Record, E> RecordMapper<R, E> 
    provide(RecordType<R> recordType, Class<? extends E> clazz)

I try to return new ActorMapper(), but javac complains:

incompatible types: com.steeplesoft.jooq.codegen.mapper.ActorMapper cannot be 
converted to org.jooq.RecordMapper<R,E>

I can cast it and it works fine, but why won't that compile. Can someone help me out? :)

CodePudding user response:

The signature you mentioned is from RecordMapperProvider, a general purpose SPI that allows for providing custom RecordMapper<R, E> instances for (RecordType<R>, Class<E>) pairs. The generics on this method are mostly for documentation purposes, meaning that for whatever you're receiving as input types, you must support in your output mapper function.

There's no way to capture the actual types you're receiving at runtime in a type safe way because your RecordMapperProvider implementation will have to decide for every input pair whether it can provide a RecordMapper, or return null if it cannot, and it can return the same RecordMapper for multiple input pairs, if that RecordMapper is sufficiently capable.

So, you'll have to unsafe cast or work with raw types.

  • Related