3

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?

4
  • 2
    You might want to swap your T and R to avoid confusion. java.util.function has the loose naming convention that T and U are inputs and R is a return value. You are essentially building a Function<R,T> Commented May 5, 2016 at 14:15
  • Suggestion: if you create variants of getFromMapping with fixed numbers of functions, you'll have a typesafe solution and do not need to cast the arguments anymore. Commented May 5, 2016 at 14:34
  • @HankD Thanks Hank, I've corrected the interface~ Commented May 5, 2016 at 15:00
  • @stholzm yeah, but I just want to make the function flexible to extend. Commented May 5, 2016 at 15:01

1 Answer 1

5

Optional#map does not modify itself, but returns a new Optional instead, so sourceWrapper still contains your continent. You should reassign the variable in the for loop:

sourceWrapper = sourceWrapper.map(function);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.