如何使用默认方法返回函数式接口的反向接口。

huangapple go评论115阅读模式
英文:

how can I return the inverse Interface of an functional Interface using default method

问题

public interface Relation<X, Y> {

	boolean test(X x, Y y);

	default Relation<X, Y> negate() {
		Relation<X, Y> relation = new Relation<X, Y>() {

			public boolean test(X x, Y y) {
				return !Relation.this.test(x, y);
			}

		};
		return relation;
	}
}

我想要使用默认方法 "negate()" 返回一个 "Relation",该方法始终返回方法 "test()" 的相反结果。我该如何实现?

public interface Relation<X, Y> {

	boolean test(X x, Y y);

	default Relation<X, Y> negate() {
		Relation<X, Y> relation = new Relation<X, Y>() {

			public boolean test(X x, Y y) {
				return !Relation.this.test(x, y);
			}

		};
		return relation;
	}
}

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

英文:

I want to return an "Relation" using the default method "negate()", which always returns the opposite of the method test(). How can I do that?

public interface Relation&lt;X,Y&gt; {

	boolean test(X x, Y y);

	default Relation&lt;X,Y&gt; negate() {
		// TODO
		Relation&lt;X, Y&gt; relation = new Relation&lt;X, Y&gt;() {

			public boolean test(X x, Y y) {
				return !this.test(x, y);
			}
			
		};
		return relation;
	}
}

I tried this code however it gives me stack overflow error

答案1

得分: 2

由于Relation目前是一个函数式接口,我们可以从negate()返回一个lambda表达式,用于反转test(...)的结果:

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

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

Ideone演示

英文:

Since Relation in its current form is a functional interface, we can return a lambda from negate() that inverts the result of test(...):

public interface Relation&lt;X, Y&gt; {
    ...

    default Relation&lt;X, Y&gt; negate() {
        return (x, y) -&gt; !this.test(x, y);
    }
    ...
}

<kbd>Ideone demo</kbd>

huangapple
  • 本文由 发表于 2020年9月4日 03:37:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/63730559.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定