Lambda只能用于功能界面? [英] Lambda can only be used with functional interface?

查看:114
本文介绍了Lambda只能用于功能界面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这样做了:

public class LambdaConflict
{
    public static void main(String args[]){
        //*
        System.out.println(LambdaConflict.get(
            (str) -> "Hello World!! By ME?"
        ));
        /*/
        System.out.println(LambdaConflict.get(new Intf<String> (){
            @Override public String get1(String str){
                return "Hello World!! By get1 " + str;
            }
        }));
        /*****/
    }

    public static String get(Intf<String> i, boolean b){
        return i.get1("from 1");
    }
}

interface Intf<T>
{
    public T get1(T arg1);

    public T get2(T arg1);
}

并获得此例外:


不兼容的类型:Intf不是函数接口
在接口Intf
中找到的多个非重写抽象方法注意:某些消息已被简化;使用-Xdiags重新编译:详细获取
完整输出
1错误

incompatible types: Intf is not a functional interface multiple non-overriding abstract methods found in interface Intf Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output 1 error

我有什么条件可以使用lambda替换匿名类?

Is there any condition that I can't use lambda to replace anonymous class?

推荐答案

不。没有办法克服这个。功能接口必须只有一个抽象方法。您的界面有两个:

No. There is no way to "overcome" this. A functional interface must have only one abstract method. Your interface has two:

interface Intf<T> {
    public T get1(T arg1);
    public T get2(T arg1);
}

注意:您无需按照注释中的说明注释您的界面。但是,如果您的接口不是有效的功能接口,则可以使用 @FunctionalInterface 注释来获取编译时错误。因此,它会为您的代码带来更多安全性。

Note: You don't need to annotate your interface as mentioned in comments. But you can use the @FunctionalInterface annotation to get compile time errors if your interface is not a valid functional interface. So it brings you a little bit more security in your code.

有关详细信息,请参阅例如 http://java.dzone.com/articles/introduction-functional-1

For more see e.g. http://java.dzone.com/articles/introduction-functional-1

这篇关于Lambda只能用于功能界面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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