如何使用默认方法返回功能接口的逆接口

时间:2020-09-03 19:37:27

标签: java functional-interface

我想使用默认方法“ 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;
    }
}

我尝试了这段代码,但是它给了我堆栈溢出错误

1 个答案:

答案 0 :(得分:2)

由于Relation的当前形式是一个功能接口,因此我们可以从negate()返回一个lambda来反转test(...)的结果:

public interface Relation<X, Y> {
    ...

    default Relation<X, Y> negate() {
        return (x, y) -> !this.test(x, y);
    }
    ...
}

Ideone demo