0

I have the following classes:

public interface Entity {
}

public class EntityImpl implements Entity {
}

public interface Service<T extends Entity> {
    T find(int id);
    Optional<T> findOptional(int id);
}

public class ServiceImpl implements Service<EntityImpl> {
    @Override
    public EntityImpl find(int id) {
        return new EntityImpl();
    }
    @Override
    public Optional<EntityImpl> findOptional(int id) {
        return Optional.of(new EntityImpl());
    }
}

public class NewMain {
    public static void main(String[] args) {
        Service service = new ServiceImpl();
        Entity e1 = service.find(1);
        Optional<Entity> opt = service.findOptional(1);
        Entity e2 = service.findOptional(1).get(); //compile error
    }
}

I can get the correct Optional type without problems if saving the optional, but if I want to call a method on the returned generic Optional it seems the compiler is loosing the type bounds and I get just an Object. In the e2-line I get the following error from javac:

incompatible types: java.lang.Object cannot be converted to Entity

Why is it loosing the type information? How can I fix this problem?

balta
  • 87
  • 1
  • 7

1 Answers1

3

You are using a raw type. You'd better go with:

Service<EntityImpl> service = new ServiceImpl();

Also, service.findOptional(1) returns a Optional<EntityImpl>, not a Optional<Entity>.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142