How can I implement a function and a BiFunction at the same time?

I created a class GenericFunctionthat implements Functionand BiFunction. But it can not be compiled.

public class GenericFunction<T, U, R> implements
        Function<T, R>, BiFunction<T, U, R> {

    @Override
    public R apply(T t, U u) {
        return null;
    }

    @Override
    public R apply(T t) {
        return null;
    }

}

Error message:

src\obscure\test\GenericFunction.java:6: error:
types BiFunction<T,U,R> and Function<T,R> are incompatible;
both define andThen(java.util.function.Function<? super R,? extends V>),
but with unrelated return types
public class GenericFunction<T, U, R> implements
       ^
where T,U,R are type-variables:
  T extends Object declared in class GenericFunction
  U extends Object declared in class GenericFunction
  R extends Object declared in class GenericFunction

1 error

How can i do this?

+4
source share
2 answers

Expanding from @romacafe's answer , I don't like GenericFunctionAndThenextends GenericFunctionwithout reusing any behavior its superclass - which looks like a bad smell to me.

Everything will be cleaner if you have implemented GenericFunctionas an interface:

public interface GenericFunction<T, U, R> extends Function<T, R>, BiFunction<T, U, R> {
    @Override
    default <V> GenericFunction<T, U, V> andThen(Function<? super R, ? extends V> after) {
        return new GenericFunction<T, U, V>() {
            @Override
            public V apply(final T t, final U u) {
                return after.apply(GenericFunction.this.apply(t, u));
            }

            @Override
            public V apply(final T t) {
                return after.apply(GenericFunction.this.apply(t));
            }
        };
    }
}

, ( andThen), ( 2 apply) , .

+5

, - , ...

, Function BiFunction andThen, , , . , . .

java- :

, , after .

... GenericFunction, .

:

public class GenericFunction<T, U, R> implements Function<T, R>, BiFunction<T, U, R> {

    @Override
    public R apply(T t, U u) {
        return null;
    }

    @Override
    public R apply(T t) {
        return null;
    }

    @Override
    public <V> GenericFunction<T, U, V>  andThen(Function<? super R, ? extends V> after) {
        return new GenericFunctionAndThen<>(after);
    }

    private class GenericFunctionAndThen<V> extends GenericFunction<T, U, V> {
        private final Function<? super R, ? extends V> after;

        public GenericFunctionAndThen(Function<? super R, ? extends V> after) {
            this.after = after;
        }

        @Override
        public V apply(T t) {
            return after.apply(GenericFunction.this.apply(t));
        }

        @Override
        public V apply(T t, U u) {
            return after.apply(GenericFunction.this.apply(t, u));
        }
    }
}

Java, ... ! ClassName.this ( ) , .

+8

Source: https://habr.com/ru/post/1623383/


All Articles