Ishant Gaurav
Ishant Gaurav

Reputation: 1203

Custom Predicate chaining

I am learning Java 8 . I am trying to create custom Predicate chaining method as below

@FunctionalInterface
public interface Predicate<T> {

    boolean test(T t);

    default Predicate<T> and(Predicate<T> other){
        return t -> this.test(t) && other.test(t);
    }
}

When i define my Predicate as above it works , but if i try to implement the same as below it gives me StackOverflow exception

@FunctionalInterface
public interface Predicate<T> {

    boolean test(T t);

    default Predicate<T> and(Predicate<T> other){
        //return t -> this.test(t) && other.test(t);
        return new Predicate<T>() {
            @Override
            public boolean test(T t) {
                return test(t) && other.test(t);
            }
        };
    }
}

Can you please explain me why it is giving me stackoverflow exception in Java 7 style whereas do not give any exception if i define it using lambda.

Upvotes: 3

Views: 374

Answers (1)

Andreas
Andreas

Reputation: 159086

test(t) is a recursive call to itself, since the unqualified call is to the anonymous class.

So would this.test(t) be, since this refers to the anonymous class.

Change to Predicate.this.test(t)

@FunctionalInterface
public interface Predicate<T> {

    boolean test(T t);

    default Predicate<T> and(Predicate<T> other){
        //return t -> this.test(t) && other.test(t);
        return new Predicate<T>() {
            @Override
            public boolean test(T t) {
                return Predicate.this.test(t) && other.test(t);
            }
        };
    }
}

See answer to "Lambda this reference in java" for more detail.

Upvotes: 6

Related Questions