2016-11-14 86 views
0

我正在玩月蚀氧气中的lambda。我有这样的代码Eclipse提取方法不适用于Lambdas

@FunctionalInterface 
interface TriFinction<O,I,J, R> { 
    R whatEver(O object, I input1, J input2); 
} 

class Dummy { 
    public String dothingsWithTwoArgs(String a, String b) { 
     return a+b; 
    } 
} 

public class LambdaTest { 
    public static void main(String[] args) { 
     Dummy::dothingsWithTwoArgs; 
    } 
} 

我无法提取Dummy :: dothingsWithTwoArgs。 Eclipse正在显示编译错误语法错误,请插入“AssignmentOperator表达式”以完成表达式,但提取在intellij中完美运行。在eclipse中有没有解决这个问题的方法?

回答

0

首先,我们注意到,您的dothingsWithTwoArgs也不是一成不变的,因此,你不应该试图调用它在一个静态的方式:你应该用你的虚拟类的实例,或使dothingsWithTwoArgs静态

这里有一些插图,这将让你去

首先,你需要有你的TriFinction作为其参数

实例的一个方法:

public static String sumToString(String a,String b, String c, TriFinction<String,String,String,String> f) { 
     return f.whatEver(a, b, c); 
    } 

其次,在哑类你需要一个你TriFinction的genric签名相匹配方法(这意味着,例如,它接收三个参数为O,J和I和它返回一个R)

例如

public static String dothingsWithThreeArgs(String a, String b,String c) { 
      return a+ " " + b + " " + c; 
     } 

现在你可以在你的主要方法使用的方法例如参考:

System.out.println(sumToString("2","3","4",Dummy::dothingsWithThreeArgs)); 

这里是您TriFinction第二插图沿着完整的例子(我猜你应该重构,重新命名为三官能:))

public class ExtractWithLambda { 
    @FunctionalInterface 
    interface TriFinction<O,I,J, R> { 
     R whatEver(O object, I input1, J input2); 
    } 

    public static String writeEqu(TriFinction<Double,Double,Double,String> f) { 
      return f.whatEver(2.5, 3.4, 5.6); 
    } 

    public static String sumToString(String a,String b, String c, TriFinction<String,String,String,String> f) { 
     return f.whatEver(a, b, c); 
    } 

    public static void main(String[] args) { 
     System.out.println(writeEqu(Dummy::writeEquation)); 
     System.out.println(sumToString("2","3","4",Dummy::dothingsWithThreeArgs)); 
    } 

} 

class Dummy { 
     public static String dothingsWithThreeArgs(String a, String b,String c) { 
      return a+ " " + b + " " + c; 
     } 

     public static String writeEquation(double a, double b, double c) { 
      return a + "*x*x " + b + "*x " + c ; 
     } 
    } 
+0

感谢您的回复。我不希望代码工作。我只需要知道为什么日食没有提取到一个变量。当我在intellij中按Ctrl + Shift + l时,它将它提取到“TriFinction dothingsWithTwoArgs = Dummy :: dothingsWithTwoArgs;”。我认为方法引用也适用于非静态方法。例如String :: toLowerCase –

0

我们应该知道一个主要的事情是编译错误消息编译器依赖。这确实意味着不同的编译器会产生不同的错误信息所有的时间。但可能会有情况。

关于您的问题,我发现这answerpost。该帖子在主题下有关此错误的详细说明不是一个声明

所以重点是这个。至于你提到的这个错误消息是具体的Eclipse编译器。编译器提出的要点是您的行只是一个表达式,不是一个语句。为了将它理解为一个声明,编译器希望你为添加一个赋值运算符。这就是insert "AssignmentOperator Expression" to complete Expression的全部含义。所以你所要做的只是将该行分配给另一个定义的变量,看起来像这样。

someVariable = Dummy::dothingsWithTwoArgs; 

希望你能找到更深入,与我提到的来源更多的例子。 :))