1

While studying Lambda expressions for Java SE 8 I came across the following text in a studybook:

Languages that support functional programming concepts have the ability to create anonymous (unnamed) functions, similar to creating objects instead of methods in Java.

I am completely lost, can someone explain what the author meant here? What's the similarity? How do they compare?

2 Answers 2

1

The wording seems particularly clumsy and I'm not entirely sure what it's trying to say. But one thing I do take from it is this notion of functions being similar to objects, in that new functions can be created on-the-fly, and functions can contain state. This is something that other languages have had for some time, but in Java it was so cumbersome as to be impractical until Java 8, with the introduction of lambdas.

Here's a JavaScript example that creates a function that has captured some state, and that modifies this state every time it's called:

function appender (str) {
    return function (s1) {
        str += s1
        return str
    }
}

jjs> var a1 = appender("foo")
jjs> var a2 = appender("bar")
jjs> a1("x")
foox
jjs> a1("y")
fooxy
jjs> a2("qq")
barqq

(I used Nashorn jjs for this, but other JavaScript implementations should work similarly.)

You can do something similar in Java as follows:

UnaryOperator<String> appender(String str) {
    StringBuilder sb = new StringBuilder(str);
    return s1 -> sb.append(s1).toString();
}

UnaryOperator<String> a1 = appender("foo");
UnaryOperator<String> a2 = appender("bar");
System.out.println(a1.apply("x"));
System.out.println(a1.apply("y"));
System.out.println(a2.apply("qq"));

The output is the same:

foox
fooxy
barqq

The Java code is more verbose, mainly because of the type declarations and things like System.out.println. And the return value isn't really a function, it's an instance of a functional interface. But the essential features are the same. And once you get used to it, you really start treating instances of functional interfaces just like functions.

Of course, it was always possible to do something like this in Java 7 or earlier, with anonymous inner classes instead of lambdas, but it was so cumbersome that virtually nobody ever thought about doing things this way.

Sign up to request clarification or add additional context in comments.

Comments

1

I believe the author may have meant that functional programming allows functions to have the same status as objects in java - i.e. they can stand on their own, without being part of a class (unlike methods in Java).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.