Lambda casting rules

前端 未结 2 1897
迷失自我
迷失自我 2020-12-31 10:05

I was curious why a lambda with a return type can not be casted to a Runnable whereas a non void method reference can.

Runnable r1 = () -> 1;         


        
2条回答
  •  时光说笑
    2020-12-31 10:16

    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.

提交回复
热议问题