0

I have a function definition which takes Optional> as a parameter.

To call the function I create:

    Optional<Map<String, String>> options = Optional.ofNullable(config.getMap(
                    OPTIONS, String.class, String.class)); 
myfunc(ImmutableMap.copyOf(options));

However I get an error: The method copyOf(Map<? extends K,? extends V>) in the type ImmutableMap is not applicable for the arguments (Optional<Map<String,String>>)

Is there a way to allow copyOf to use Optional map ?

user1692342
  • 5,007
  • 11
  • 69
  • 128
  • 1
    You have to copy the wrapped object, not the Optional itself. For example, `Optional> copy = options.isPresent() ? Optional.of(ImmutableMap.copyOf(options.get())) : Optional.empty();`. – teppic Nov 18 '16 at 01:52
  • @teppic Thanks. It is Optional> copy – user1692342 Nov 18 '16 at 02:09
  • 1
    You should not use an optional map at all. The canonical representation of an absent map is an empty map, which works for most use cases. – Holger Nov 18 '16 at 11:31
  • [`Optional` should not be used as a method arguments.](http://stackoverflow.com/questions/31922866/why-should-java-8s-optional-not-be-used-in-arguments) – Didier L Nov 18 '16 at 14:43
  • Also, even @teppic's solution is a contrived way of reimplementing `Optional.map()`. Using `Optional.isPresent()` followed by `Optional.get()` is a bad smell and most often bad usage of the API. They might deprecate `Optional.get()` to discourage this. – Didier L Nov 18 '16 at 14:46

0 Answers0