Lambda casting rules

别说谁变了你拦得住时间么 提交于 2019-11-30 08:48:23

The Runnable interface defines the run method with return type void. In a lambda expression that means that the part following the arrow -> must be a statement. This is explained in JLS §15.27.3:

If the function type's result is void, the lambda body is either a statement expression (§14.8) or a void-compatible block.

The JLS $14.5 clearly defines the syntax of a statement. As explained above it must be an "ExpressionStatement" (§ 14.8). Looking there, you can find that a simple literal is not an adequate expression, but a method invocation is (even if it returns something).

This is not really a “special” rule for Lambdas. It has always been acceptable to use a non-void method in a statement context (in which case, the return value is thrown away), but not so with a simple expression. For instance “String.valueOf(true);” is a valid java statement, that may occupy a line by itself, whereas “true;” is not and may not.

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