vagavince vagavince - 7 months ago 33
Java Question

Why do I need to implement Apply in Java Guava function?

For example, following is the standard pattern

Function<Integer, Integer> powerOfTwo = new Function<Integer, Integer>() {
public Integer apply(Integer input) {
return (int) Math.pow(input, 2);

What is the advantage of implementing apply? Wouldn't it be cleaner to write

Function<Integer, Integer> powerOfTwo = new Function<Integer, Integer>(Integer input) {
return (int) Math.pow(input, 2);


Yes, of course, but this is how the Java language worked, at least until lambdas were introduced in Java 8. This has nothing to do with Guava and everything to do with the Java language.

As of Java 8, you could just write

Function<Integer, Integer> powerOfTwo = input -> (int) Math.pow(input, 2);

...but if you're not on Java 8, then the way the language is designed makes it so you have to write the first version.