0

In a piece of Java code I inherited, I encountered the following what seems to be a Lambda expression:

id ->""

Appearing as a parameter to a method:

runner.setIntanceName(id ->"")

I consulted the Lambda Expressions documentation but could not find the meaning of this special expression.

What does id ->"" mean?

2

4 Answers 4

2

E.g. you have:

public static void setIntanceName(Function<String, String> function) {
    function.apply("aaa");
}

Then to use this method: setIntanceName(id -> "") or

setIntanceName(new Function<String, String>() {
    @Override
    public String apply(String id) {
        return "";
    }
});

I.e. you add a function to the method (or treat it as instance of some interface with only one method - it is called functional interface). Method setIntanceName will use this function. In given example, this function accepts id=aaa and returns always empty string as function's result.

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

4 Comments

To be clear, the lambda turns an empty string; it is not just an empty string in the body.
@MattSmeets you probably meant "returns" and not "turns" :)
Thank you, so if I understand your answer correctly, all that (id -> "") means is: "Accept any string as a parameter but always return an empty string"?
Yes, simplified this code looks like runner.setInstanceName("")
1

The left side specifies the parameters required by the expression, which could also be empty if no parameters are required.

The right side is the lambda body which specifies the actions of the lambda expression.

so here id ->"" id is empty string.

read more about it here

2 Comments

Thank you. I understand the parameter (left side) part. But what does an "empty string" action mean?
As you see in the answer its mean specifies the actions such as any statement or expression. id->id+1 or id->"test" or ...
1

I think that person, who have written that intended to ignore any id-arguments and return just an empty string.

Comments

0

-> is just the token that separates the parameters from the body. See the part Syntax of Lambda Expressions in the very documentation you linked to https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html

"" is the body. In this case, a constant empty string.

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.