Consider the abstract class:
public abstract class Animal { ...}
and the interface:
public interface Canine<T extends Animal> {...}
I've defined the concrete classes:
public class Dog extends Animal implements Canine<Dog> {...}
public class Wolf extends Animal implements Canine<Wolf> {...}
I'd like to build a repository class that accesses the database of animals and returns them. I've defined it in the following way:
public interface Repository {
Option<Dog> findById(String id, Class<Dog> type);
Option<Wolf> findById(String id, Class<Wolf> type);
(note: Option is taken from the vavr library)
This repository is used in the following class:
public abstract AbstractFinderClass<T extends Animal & Canine<T>> {
private Class<T> animalType;
public AbstractFinderClass(Class<T> animalType) {
this.animalType = animalType;
}
public Option<T> findMyAnimal(String id) {
return repository.findById(id, this.animalType);
}
}
which in turn is implemented in concrete form with:
public class DogFinder extends AbstractFinderClass<Dog> {
public DogFinder() {
super(Dog.class);
}
}
Now, the line return repository.findById(id, this.animalType) causes two errors:
- on the second parameter,
this.animalTypeis of typeClass<T>while the expected type isClass<Dog>, and these are apparently incompatible; - the return type is expected to be
Option<T>while instead I getOption<Dog>
I am afraid I am missing some "little" detail, as I would expect Dog and T to be compatible.
Could you help me in fixing the problem?
Repositoryclass is supposed to be implemented. Shouldn't thefindByIdmethods have the same type erasure?Option<A> findById<A>(String id, Class<A> type);.Tis possible to be a type that is not defined in yourRepository, so you would try to execute method that doesn't exist.DogFinderis supposed to be a concrete implementation ofAbstractFinderClass, why doesn't it have anextendsclause? We can't be sure that yourTisDog. In fact, why does it even haveDogas a generic parameter? That would create confusion with theDogclass. Your code wouldn't actually compile. I suggest a minimal reproducible example.