在log4j2中,我们有一个方便的特性,它被描述为

// Java-8 style optimization: no need to explicitly check the log level:
// the lambda expression is not evaluated if the TRACE level is not enabled
logger.trace("Some long-running operation returned {}", () -> expensiveOperation());

我在Kotlin 使用这一点的try

log.debug("random {}", { UUID.randomUUID() })

哪个会打印

random Function0<java.util.UUID>

How do we use lambda argument logging with kotlin? Or how do we explicitly tell kotlin what method to call?

推荐答案

The problem is that debug() is overloaded, and has another method taking a vararg Object as argument. Kotlin chooses that overload rather than the one taking a Supplier<?> as argument, because it doesn't know that the lambda expression is supposed to be a Supplier.

Just specify it as a Supplier:

log.debug("random {}", Supplier { UUID.randomUUID() })

Kotlin相关问答推荐

创建具有共同父类型的两种不同类型对象的列表的最有效方法是什么?

何时使用figureEach

编译后的JavaFX应用程序立即以静默方式崩溃

Kotlin:将泛型添加到列表任何>

Mockk:对同一函数进行两次存根会忽略第一个行为

如何将消费者放入 Kotlin 的 map 中?

如何将 `when` 与 2 个密封类一起使用并获取内部值?

从 Java 调用 Kotlin 高阶函数

如何在调试中修复 ClassNotFoundException: kotlinx.coroutines.debug.AgentPremain?

如何退出 Kotlinc 命令行编译器

零安全的好处

DatabaseManager_Impl 不是抽象的,不会覆盖 RoomDatabase 中的抽象方法 clearAllTables()

如何解决此错误请Kotlin:[Internal Error] java.lang.ExceptionInInitializerError

如何捕获传递给模拟函数的参数并返回它?

如何暂停kotlin coroutine直到收到通知

空对象引用上的 TransitionSet ArrayList.size()

保存对象时未填充 Spring Boot JPA@CreatedDate @LastModifiedDate

在 Kotlin 中返回函数有不那么丑陋的方法吗?

在android java类中使用Kotlin扩展

函数引用和lambdas