我想看看在 Scala 和 Java 之间将函数作为参数传递的区别。几年前我搬到了 Scala,与 Java 接触不多。我可以在方法之外使用 Lambda 表达式吗,如下所示?它编译并工作正常,但它有什么问题吗?到目前为止,我看到的所有示例都在方法中包含了 Lamda。下面的代码只是一个例子,我知道你可以用 供应商界面。
@FunctionalInterface
public interface IFunc {
String printMessage();
}
public class JavaFunc {
public String message() {
return functionA(functionB);
}
IFunc functionB = () -> "Hi, I am functionB from Java, I am passed to functionA as a parameter.";
public String functionA(IFunc funcB) {
return funcB.printMessage();
}
}
最佳答案
你可以在类的任何地方声明lambda表达式
If you declare inside a method (which is similar to local variables, scope inside of method)
public String message() {
IFunc functionB = () -> "Hi, I am functionB from Java, I am passed to functionA as a parameter.";
return functionA(functionB);
}
If you declare in the class (Which is similar to instance variables that can be accessed in all instance methods directly and with object reference in static area )
public class JavaFunc {
IFunc functionB = () -> "Hi, I am functionB from Java, I am passed to functionA as a parameter.";
public String message() {
// use here functionB
return functionA(functionB);
}
示例: Predicate
和匿名内部类的 lambda 表达式
p1,p2 are at instance level and p3,p4 are local
public class DemoMain {
Predicate<Integer> p1 = i -> i > 5;
Predicate<Integer> p2 = new Predicate<Integer>() {
@Override
public boolean test(Integer t) {
// TODO Auto-generated method stub
return false;
}
};
public static void main(String args[]) {
DemoMain m = new DemoMain();
System.out.println(m.p1.test(10));
System.out.println(m.p2.test(10));
}
public void m1() {
System.out.println(p1.test(10));
System.out.println(p2.test(10));
Predicate<Integer> p3 = i -> i > 5;
Predicate<Integer> p4 = new Predicate<Integer>() {
@Override
public boolean test(Integer t) {
// TODO Auto-generated method stub
return false;
}
};
}
}
关于java - Lambda 表达式必须在方法内部吗?它们可以作为类的成员存在于方法之外吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53982169/