JonJavaK JonJavaK - 1 year ago 102
Java Question

Chaining Functional Interfaces - IntUnaryOperator vs UnaryOperator

I'm still learning functional interfaces. I'd like to know why I'm able to chain a

UnaryOperator
to the end of a
Function
, but not an
IntUnaryOperator
to the end of the same Function.

UnaryOperator <String> twoOfMe = s -> s + s;
Function <String, Integer> convertMe = s -> Integer.parseInt (s);

UnaryOperator <Integer> twiceMe = n -> 2*n;

IntUnaryOperator doubleMe = n -> 2*n;

int a = twoOfMe.andThen(convertMe).andThen(twiceMe).apply ("2");

int b = twoOfMe.andThen(convertMe).andThen(doubleMe).apply ("2");





int a
works with
twiceMe
but
int b
doesn't work with the
doubleMe
.

Thanks

Edit:
It says incompatible types. Required int. Found java.lang.Object

Answer Source

andThen(Function<? super R, ? extends V> after) expects a Function argument. UnaryOperator<Integer> is a sub-interface of Function<Integer,Integer>, which matches. IntUnaryOperator has no relation to the Function interface, so doubleMe cannot be passed to andThen.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download