gpt4 book ai didi

java - 任何人都可以解释这个声明 - "The point of all lambdas is deferred execution"

转载 作者:行者123 更新时间:2023-12-01 08:41:51 24 4
gpt4 key购买 nike

我正在查看“ Java SE 8 for the really Impatient: Programming with Lambdas ”中的一个例子。

Let us look at a simple example. Suppose you log an event:

logger.info("x: " + x + ", y: " + y);

What happens if the log level is set to suppress INFO messages? The message string is computed and passed to the info method, which then decides to throw it away. Wouldn’t it be nicer if the string concatenation only happened when necessary?

Running code only when necessary is a use case for lambdas. The standard idiom is to wrap the code in a no-arg lambda:

() -> "x: " + x + ", y: " + y

The following method provides lazy logging:

public static void info(Logger logger, Supplier<String> message) {
if (logger.isLoggable(Level.INFO))
logger.info(message.get());
}

We use the isLoggable method of the Logger class to decide whether INFO messages should be logged. If so, we invoke the lambda by calling its abstract method, which happens to be called get.



所以我不明白的是 - 我们可以使用 logger.isLoggable(Level.INFO)在示例 1(不使用 lambdas 的代码)中,只有当我们 logger.isLoggable(Level.INFO) 时才会计算消息字符串很满意。
logger.info("x: " + x + ", y: " + y);

在这种情况下使用 lambda 有什么用?

最佳答案

据我所知,这完全是关于 Supplier以及你可以推迟执行的方式。 IMO 更好的例子是 Optional两种方法:orElseorElseGet .
orElse返回 T或者在你的例子中是 String ;另一方面orElseGet返回 Supplier<T> , 仅在需要时计算(当 Optional 实际丢失时):

public T orElseGet(Supplier<? extends T> supplier) {
return value != null ? value : supplier.get();
}

这里的区别在于 orElse总是计算值,有点像急切地;即使它不需要。

关于java - 任何人都可以解释这个声明 - "The point of all lambdas is deferred execution",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44378418/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com