首页 > 解决方案 > 使用 lambda 表达式打印布尔值

问题描述

在 java 中,您可以像这样打印一个布尔值:

System.out.println(1 == 1);

但是,如果我尝试使用 lambda 表达式来实现这一点,则会出现错误:

System.out.println(() -> 1 == 1);  // the `() -> 1 == 1` expression should return `true`

为什么我不能这样做?

标签: java

解决方案


lambda 表达式必须具有某种功能接口(它实现的接口)的类型。

由于没有重载println将函数接口作为参数,编译器不知道应该由你的 lambda 表达式实现的函数接口的类型。

您可以按如下方式指定它:

System.out.println((Supplier<Boolean>) () -> 1 == 1);

或者

Supplier<Boolean> sup = () -> 1 == 1;
System.out.println(sup); 

当然,您将打印功能接口实例,而不是boolean值。

要打印boolean您可以编写的值:

Supplier<Boolean> sup = () -> 1 == 1;
System.out.println(sup.get()); 

推荐阅读