Home > Mobile >  Java -> operator
Java -> operator

Time:04-22

I know that -> is used for lambda expressions with the syntax ()->{}.

But I saw this code: file -> file.isFile() - with no () and {}. What does it do?

Thanks!

CodePudding user response:

() is not required when you have a single argument and {} is not required when your lambda body is a single expression.

See the Java tutorial for further information and the Java Specification for a more formal description of the syntax.

CodePudding user response:

As Federico answered, for the single arguments you do not need () and for the statements only return a value and do not do anything else, you do not need {}.

The addition I wanna make to his contribution:

The code you put means, There is a function, that takes file as a parameter. Then, returns its .isFile().

In other words, you can also reach the same aim by defining a method:

<private/protected/public> boolean myLovelyMethod(File file){
    return file.isFile();
}

Lambda function just makes it a little bit shorter. If you are not going to re-use the method, may be better to use lambda.

  • Related