Java partial function application

I’ve have made a small experiment with Java 8 lambda features and as a result I’ve created this small utility library that implements pretty simple partial function application paradigm. It won’t be as much flexible as in other languages (like Scala) since the implementation is library based and Java does not have any language level support for this. So the constraint at this moment are that the function can take up to 5 different arguments.

Let’s see the code:

Providing that we have a simple matematic function:

public int substract(int a, int b) {
    return a - b;

We can use the method reference, assing it to functional interface and invoke it:

int sum = Partial.function(this::substract)
        .apply(1, 2);

The same effect we can achieve by applying arguments one by one and invoke the function at the end:

int sum = Partial.function(this::substract)

It’s even possible to apply the arguments from “right to left”:

int sum = Partial.function(this::substract)

What is noticable, and I wasn’t fully aware of this, is that you can assign varargs method reference to a functional interface having any number of arguments. Below are all valid assigments:

Function f = Functions::funcVarArgs;
Function1<String, String> f1 = Functions::funcVarArgs;
Function2<String, String, String> f2 = Functions::funcVarArgs;

You don’t have to use the Partial and directly assing the lambda or method reference to one of the Function interfaces. Although the Partial class creates a nice form of DSL for invoking the method in place.

The partial applications are staticly typed, example:

public String url(String scheme, String host, int port, String username, String repo) {
        return String.format("%s://%s:%d/%s/%s", scheme, host, port, username, repo);

String url = Partial.function(this::url)

The source code is available at the Github:

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s