Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 630
alwayscurious Avatar asked Aug 17 '17 07:08

alwayscurious


2 Answers

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.

like image 132
Eran Avatar answered Sep 30 '22 07:09

Eran


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");
like image 41
Dorian Gray Avatar answered Sep 30 '22 05:09

Dorian Gray