Definition in class:
class XXX {
Map<String, Class> someMap;
public <K, V>
Optional<V> get(K key) {
return Optional.ofNullable(getNullable(key));
}
public <K, V>
V getNullable(K key) {
//someMap already holds key -> class of V
String value = DB.fetch(key);
return gson.fromJson(value, someMap.get(key.toString()));
}
}
Usage:
//xxx is an instance of XXX
Optional<ClassA> valueOpt = xxx.get(key); //this is fine
ClassA value = valueOpt.get(); //this is fine
//The intermediate valueOpt seems redundant, try to bypass it.
ClassA value = xxx.get(key).get(); //this does not work
My question: in the last line, seems the type info is deducible, why cannot it work? any workaround to make it work in one line?
Workarounds summary:
1) xxx.get(key, ClassA.class)
2) (ClassA)xxx.get(key)
3) xxx.<K,ClassA>get(key)
I still feel those are all workarounds because ClassA value = xxx.getNullable(key);
can work.