Objects as Functions in Java

Earlier this year I wrote a build tool in java. The core idea at the time was to express the build in terms of functions and function composition. This is not exactly a good fit with java. So last week I had some spare time and came up with this way of defining a function (application) in java:

 public static class FancyFunction extends FunctionBase {
        @In
        public final Str a;
        @In
        public final Str b;
 
        @Out
        public final Str c = null;
        @Out
        public final Str d = null;
 
        public FancyFunction(Str a, Str b) {
            this.a = a;
            this.b = b;
            super.reflect();
        }
 
        protected void evaluate() {
            setResult(c, new StrImpl(a.getValue() + "-" + b.getValue()));
            setResult(d, new StrImpl("XX"));
        }
    }

There is obviously a lot of magic going on and I do feel a bit bad abou setting final fields using reflection.

What it actually does is defining two functions. In a friendlier syntax somwhat like this:

fancy.c(a, b) = a + "-" + b;
fancy.d(a, b) = "XX";

But back to the java example, you can now compose applications like this:

FancyFunction fun = new FancyFunction(new StrImpl("x"), new StrImpl("y"));
FancyFunction fun2 = new FancyFunction(fun.c, new StrImpl("z"));
assertEquals("x-y-z", fun2.c.getValue());

As this is all very reflective I could actually traverse the metadata and get dot to render this:

test

There is no code, as it is all very dirty. But to me it looks like a viable syntax for specifying tasks and wrapping imperative code into a functional style. The current implementation relies heavily on interfaces, because it generates a lot of proxies that allow for lazy evaluation.


Posted

in

by

Tags:

Comments

One response to “Objects as Functions in Java”

  1. Tiest Avatar
    Tiest

    You know, I like what you’re trying to do, but it really highlights for me some of the arse-about-face things that Java does. The FancyFunction definition is horrendous, but only because you have to subvert Java so much.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.