Search code examples
javaguavaoption-typenull-object-pattern

How to use Guava Optionals in a non-generic context?


I'm trying to use the Null-Objects from guava in the following method:

private void display(Optional<String> message) {
  ...
}

The method in which I am calling the method display(..) looks like this:

if(...) {
  display(Optional.of("hello");
} else {
  display(Optional.absent());
}

Now I'm getting the following compiler error:

The method display(Optional<String>) in the type TokenServlet is not
applicable for the arguments (Optional<Object>)

The only compiling workaround I have found is to use

Optional.fromNullable((String) null)

instead of

Optional.absent()

Is there really no other possibility if I'm using Optionals in a non-generic context?


Solution

  • You can do this:

    display(Optional.<String> absent());