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
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
.
This is because IntUnaryOperator
maps an int
to an int
, and Function <String, Integer> convertMe
is returning an Integer
, not an int
. You cannot chain them.
You can declare ToIntFunction<String> convertMe = Integer::parseInt;
, then you could chain them.
UnaryOperator<String> twoOfMe = s -> s + s;
ToIntFunction<String> convertMe = Integer::parseInt;
IntUnaryOperator doubleMe = n -> 2*n;
int b = twoOfMe.andThen(convertMe).andThen(doubleMe).apply ("2");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With