java - 使用 lambda 表达式打印布尔值
问题描述
在 java 中,您可以像这样打印一个布尔值:
System.out.println(1 == 1);
但是,如果我尝试使用 lambda 表达式来实现这一点,则会出现错误:
System.out.println(() -> 1 == 1); // the `() -> 1 == 1` expression should return `true`
为什么我不能这样做?
解决方案
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());
推荐阅读
- c++ - 为什么 DestroyWindow 被阻止?
- xamarin.forms - Xamarin Forms Android WebViewRenderer inside ScrollView 截断内容
- oauth - 即使放置了 Client ID 和 Client Secret,为什么 Firebase 登录方法显示 Client ID 和 Client Secret 是必需的?
- python - 哪个是在 Python 中并行运行多个任务的最佳方式
- javascript - 停止传播包含工具提示且链接在 Button 上不起作用的按钮
- javascript - How can I change the CHANGE ME text inside my script
- php - 尝试使用 Laravel eloquent 关联表列和总和
- entity-framework - EF Core:聚合聚合
- python - python中的曲面图和颤动图不起作用
- mysql - 为什么我们需要嵌套的 Select 语句?