In the following code, I tried to call the info method taking a Supplier. (The info method is overloaded: one is taking a String and the other is taking a Supplier.) The compiler complains that "The method info(String) is not applicable for the argument Supplier<Double>
". My expectation is to call the info method taking a Supplier by sending a Supplier object. Can I get some help to understand this error?
Supplier<Double> randomSupplier = new Supplier<Double>()
{ public Double get()
{ return Math.random(); }
};
logger.info(randomSupplier); <----
Assuming that your logger
is a java.util.logging.Logger
. . .
According to the Javadoc for Logger.info
, it expects a Supplier<String>
, and you're giving it a Supplier<Double>
.
To fix this, you need to give it a Supplier<String>
. You can write one either like this:
final Supplier<String> randomSupplier =
new Supplier<String>() {
public String get() {
return Double.toString(Math.random());
}
};
or like this:
final Supplier<String> randomSupplier =
() -> Double.toString(Math.random());
You can even write:
logger.info(() -> Double.toString(Math.random()));
and Java will magically infer that your lambda is meant to be a Supplier<String>
(because the other overload of info
doesn't take a functional interface type).