Java 17
I'm implementing the following method:
public static <T, O extends T, V> Optional<V> toOption(T t, Function<? super O, ? extends Optional<V>> f, Class<O> cls){
Optional<O> opt;
if(cls.isAssignableFrom(t.getClass())){
opt = some((O) t);
} else
opt = empty();
return opt.flatMap(f);
}
which is supposed to return non empty Optional if the runtime type of argument of type T
is subclass of type parameter O
and flatMap it with the given Function
. The problem with this implementation is that the following still compiles:
toOption(123, v -> Optional.of(v), String.class);
But Integer
and String
are unrelated. So O extends T
does not really works. Is there a way to make such cases not compile?