IsaacLevon
IsaacLevon

Reputation: 2570

Understanding andThen() function

Consider the following example:

public static void main(String[] args) {
    Function<String, Integer> f1 = str ->  str.length();
    f1.andThen(i -> {
        System.out.println("length is " + i);
        return "why do I need to return a String here?";
    }).apply("12345");
}

I'm trying to understand why do I have to return String.

What's the logic behind that? I'd expect that andThen would accept a Consumer<Integer> let's say or something similar.

So why do andThen() requires me to return the type of the original input?

Upvotes: 1

Views: 729

Answers (1)

Michael
Michael

Reputation: 44150

What you want can be achieved via

Function<String, Integer> f1 = str ->  str.length();
Consumer<Integer> printer = i -> System.out.println("length is " + i);
printer.accept(f1.apply("12345"));

andThen is for chaining functions together. Functions always have results.

Upvotes: 5

Related Questions