英文:
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<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;
}
}
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);
}
...
}
英文:
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<X, Y> {
...
default Relation<X, Y> negate() {
return (x, y) -> !this.test(x, y);
}
...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论