为什么以下使用方法引用的转换不会产生编译错误? [英] Why does the following casting with method reference not produce a compilation error?

查看:142
本文介绍了为什么以下使用方法引用的转换不会产生编译错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class SomeClass{

    public static int someFunction(int a) {
        return a;
    }

    public static void main(String[] args) {    
        Consumer<Integer> c = SomeClass::someFunction; 
    }
}

我不明白为什么:消费与LT;整数> c = SomeClass :: someFunction;
不会产生编译错误,因为函数someFunction是一个带返回值的方法,而Consumer表示没有返回值的方法

I'm not getting why: Consumer<Integer> c = SomeClass::someFunction; is not producing a compilation error, since the function someFunction is a method with return value, and Consumer is representing methods with no return value

推荐答案

来自规范


如果lambda的主体是一个声明表达式(即,允许独立作为语句的
表达式),它与
兼容,产生void的函数类型; 任何结果都只是
丢弃。

方法引用也是如此。

这种方式更灵活。假设在正常调用方法时不使用返回值是一个编译器错误 - 那将是非常烦人的。在某些情况下,你最终不得不使用你不关心的伪变量。

It's more flexible that way. Suppose it was a compiler error to not use a return value when you called a method normally - that would be incredibly annoying. You'd end up having to use fake variables you didn't care about in some cases.

public class SomeClass
{
    public static int someFunction(int a) {
        return a;
    }

    public static void main(String[] args) {    
        someFunction(3); // "error" - ignoring return type
        int unused = someFunction(3); // "success"
    }
}

如果你想要一个完整的正式定义可接受的内容,参见 15.13.2。方法参考的类型

If you want a the full formal definition of what is acceptable, see 15.13.2. Type of a Method Reference.

这篇关于为什么以下使用方法引用的转换不会产生编译错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆