Mirco Widmer
Mirco Widmer

Reputation: 2149

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?

Upvotes: 0

Views: 175

Answers (2)

Nouish
Nouish

Reputation: 71

You can do this:

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

Upvotes: 3

Ali Arda Orhan
Ali Arda Orhan

Reputation: 784

I think you try to pass unvalid parameter to method. You have to wrap it in method. It will solve the issue.

private void display(String message) {
 Optional<String> optionalMessage=Optional.fromNullable(message);
  ...
}

Upvotes: 0

Related Questions