我想使用默认方法“ negate()”返回“关系”,该方法总是返回方法test()的反面。我该怎么办?
public interface Relation<X,Y> {
boolean test(X x, Y y);
default Relation<X,Y> negate() {
// TODO
Relation<X, Y> relation = new Relation<X, Y>() {
public boolean test(X x, Y y) {
return !this.test(x, y);
}
};
return relation;
}
}
我尝试了这段代码,但是它给了我堆栈溢出错误
答案 0 :(得分:2)
由于Relation
的当前形式是一个功能接口,因此我们可以从negate()
返回一个lambda来反转test(...)
的结果:
public interface Relation<X, Y> {
...
default Relation<X, Y> negate() {
return (x, y) -> !this.test(x, y);
}
...
}