定义 lambda 时是否可以调用默认方法?
例如
@FunctionalInterface
public interface StringCombiner {
String combine(String s1, String s2);
default String bar(String s1, String s2) {
return combine(s1,s2);
};
}
我想做这样的东西:
StringCombiner sc = (s1, s2) -> /** I want to call bar() here **/
最佳答案
这将导致 StackOverflowError :bar
调用 combine
,后者又调用 bar
,后者又调用 combine
。 ..
您需要在其定义中递归引用 sc
(您不能在 lambda 中使用 this
来引用由 lambda 创建的对象)。我相信这只有在实例或类变量中才有可能。所以它可能看起来像:
@FunctionalInterface
public interface StringCombiner {
String combine(String s1, String s2);
default String bar(String s1, String s2) { return "bar"; }
}
//Note: you need the static block to avoid a "self-reference" compilation error
static StringCombiner sc;
static {
sc = (s1, s2) -> sc.bar(s1, s2) + s1 + s2;
}
public static void main(String[] args) {
System.out.println(sc.combine("a", "b"));
}
打印barab
。
关于java - 从 lambda 调用默认方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21776637/