Search code examples
javalambdajava-streamfunctional-interface

Cast context of functional interface in lambda expression


There's an example of casting a functional interface (as I understand it) in a cast context: https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html with a code example:

 // Cast context
 stream.map((ToIntFunction) e -> e.getSize())...

It is described as "Functional interfaces can provide a target type in multiple contexts, such as assignment context, method invocation, or cast context".

I've tried to use ToIntFunction with stream().mapTo() but could only use it with stream().mapToInt() and also not using the cast.

Could someone please provide an example how to use the cast context example? I've tried this:

// dlist is a list of Doubles
dlist.stream().map((ToIntFunction) d -> d.intValue()).forEach(System.out::println)

but it works without (ToIntFunction). When do I need the cast context anyway?

Also what is the purpose of mapToInt. This seems to be equivalent:

dlist.stream().mapToInt(d -> d.intValue()).forEach(System.out::println);

dlist.stream().map(d -> d.intValue()).forEach(System.out::println);

Solution

  • Cast context it means that Java Compiler will auto convert functional interface to the target functional interface type,

    As (ToIntFunction) d -> d.intValue(), the compiler will auto convert it to: ToIntFunction toIntFunction = (ToIntFunction<Double>) value -> value.intValue()

    so:

    dlist.stream().map((ToIntFunction) d -> d.intValue()).forEach(System.out::println)
    

    it's equal to:

    ToIntFunction toIntFunction = (ToIntFunction<Double>) value -> value.intValue();
    dlist.stream().mapToInt(toIntFunction).forEach(System.out::println);
    

    And for:

    dlist.stream().mapToInt(Double::intValue).forEach(System.out::println);
    dlist.stream().map(Double::intValue).forEach(System.out::println);
    
    • mapToInt's Double::intValue compiler will convert it to ToIntFunction<Double>.
    • map's Double::intValue compiler will convert it to Function<Double, Int>