【问题标题】:how can I return the inverse Interface of an functional Interface using default method如何使用默认方法返回功能接口的逆接口
【发布时间】:2020-09-03 19:37:27
【问题描述】:

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

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

【问题讨论】:

  • return !this.test(x, y); 中,this.test 是您定义的默认方法,因此它是无限递归。
  • default Relation&lt;X, Y&gt; negate() { return (x, y) -&gt; !this.test(x, y); }

标签: java functional-interface


【解决方案1】:

由于当前形式的Relation 是一个函数式接口,我们可以从negate() 返回一个与test(...) 的结果相反的lambda:

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

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

Ideone demo

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-18
  • 1970-01-01
  • 1970-01-01
  • 2018-09-06
  • 2019-01-28
  • 2014-12-06
  • 1970-01-01
相关资源
最近更新 更多