7
 public static <T, U, R> Function<U, R> partial(BiFunction<T, U, R> f, T x) {
        return (y) -> f.apply(x, y);
    }

In the expression above, I can understand that function partial returns another function, Function<U, R>. That Function<U, R> itself returns a value of R. What does the rest static <T, U, R> stand for? I mean if Function<U, R> returns an R what is the deal with <T, U, R> ?

microwth
  • 1,016
  • 1
  • 14
  • 27

1 Answers1

7

(I know it's not technically correct in Java terminology, but I'm going to say "argument" below where I mean "formal parameter" because mixing "formal parameter" and "type parameter" everywhere is confusing.)

T is the type parameter for the x argument.

partial accepts two arguments:

  • f, a function that accepts a T and a U and returns an R:
    BiFunction<T, U, R> f

  • x, which is of type T:
    T x

partial returns a new function that only accepts a U (not a T and a U) and returns R. Instead of expecting a T argument, the new function uses the x provided to partial when calling f.

In short: It returns a new function in which the first argument (of type T) has been partially-applied (curried) via partial's x argument.

The reason we have <T, U, R> near the beginning of the declaration is that that's how Java syntax lets us specify that partial is a generic method, using type parameters T, U, and R (otherwise, they look like type names, not type parameters).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • so in "static " the T is replaced by "BiFunction f" and U="T x" ? – microwth Apr 11 '16 at 10:21
  • 1
    @microwth: No, `T`, `U`, and `R` are all specified when the method is called, to give concrete types for those type parameters. What `partial` does is return a function accepting `U` and returning `R` that calls the original function accepting `T` and `U` and returning `R` with the specified value of `x`. E.g., if I have a method `Widget foo(String, List)`, I could use `partial` to get a ``Widget partialFoo(List)` that will call `foo` with `x` as the string. More in the generics tutorial: https://docs.oracle.com/javase/tutorial/extra/generics/methods.html – T.J. Crowder Apr 11 '16 at 10:29
  • @t-j-crowder "that calls the original function" you mean function "f"? So it's like "return (y) -> f.apply(x, y);" is "Function" and then ,when f.apply(x, y) runs it returns a value ,so it becomes return (y)->value, which is a function that satisfies the static . Is that correct ? – microwth Apr 11 '16 at 11:24
  • @microwth: `(y) -> f.apply(x, y)` creates a function, which is what `partial` returns. The function accepts `y`. The body of the function is effectively `return f.apply(x, y);` So when you call the function `partial` returns, it calls `f`, passing in `x` (the one you gave `partial`) for the first argument and `y` (the one you gave when calling the function `partial` returns) as the second argument, and then it returns whatever `f` returns. – T.J. Crowder Apr 11 '16 at 12:20