Reputation: 28541
I can't find the trick here: I want a function to return a list of optional objects in order to mean that my list does contain this many elements but that some of them are not valid.
public Optional<String> getMyObjects() {
List<Optional<String>> result = Lists.newArrayListWithCapacity(2);
result.add(Optional.of("This value is valid"));
result.add(Optional.absent()); // Compiler error
return result;
}
This does not compile:
The method add(Optional<String>) in the type List<Optional<String>> is not
applicable for the arguments (Optional<Object>)
How would you put it? I have tried casting without success
Upvotes: 3
Views: 1167
Reputation: 691785
Use
result.add(Optional.<String>absent())
to force the generic type.
Or, to let the compiler infer it:
Optional<String> o = Optional.absent();
result.add(o);
Upvotes: 4
Reputation: 53829
Try:
result.add(Optional.<String> absent());
The absent() method is parametrized.
Upvotes: 3
Reputation: 28005
Try:
result.add(Optional.<String>absent());
Read more about parametrized methods and explicit type argument specification in great yet unofficial Java Generics FAQ.
Upvotes: 8