Continent is a composite Object. Structure is :
Continent
--Country
----State
------Town
so in this notation:
town= Optional.of(continent)
.map(Continent::getCountry)
.map(Country::getState)
.map(State::getTown)
.orElse(null);
this works fine, but when I try to write a general mapper,
public static <T, R> T getFromMapping(R source,
T defaultValue,
Function<?,?>... functions) {
Optional sourceWrapper = Optional.ofNullable(source);
for (Function function : functions) {
sourceWrapper.map(function);
}
return (T) sourceWrapper.orElse(defaultValue);
}
and invoke it by
portfolio = getFromMapping(continent, null,
((Function<Continent, Country>) Continent::getCountry)
((Function<Country, State>) Country::getState),
((Function<State, Town>) State::getTown));
it compile just fine but don't work. The mapper jump to second step to and said Continent could not cast to country, why? there supposed to be no cast while doing mapping, how to fix it?
TandRto avoid confusion.java.util.functionhas the loose naming convention thatTandUare inputs andRis a return value. You are essentially building aFunction<R,T>getFromMappingwith fixed numbers of functions, you'll have a typesafe solution and do not need to cast the arguments anymore.