(Java 8) java.util.function.Supplier

不羁的心 提交于 2021-02-07 11:05:37

问题


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); <----

回答1:


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).




回答2:


You can try this way getting Supplier in java 8 way and logging by converting Supplier to String

Supplier<Double> randomSupplier = () -> Math.random();
info(randomSupplier);

  private void info(Supplier<Double> randomSupplier) {
    System.out.println(randomSupplier.get());
 }


来源:https://stackoverflow.com/questions/52130659/java-8-java-util-function-supplier

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!