Lambda只能用于功能界面

Lambda只能用于功能界面

本文介绍了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);
}

并获得此例外:

我有什么条件可以使用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.

有关详细信息,请参阅例如

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

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

09-01 16:19