Sunday, December 9, 2018

Lambda Syntax

Let's make it more sensible and understand the lambda expression, let's discuss the syntax first by starting from the initials:

lambdaHolderVariable = public void greet(){
System.out.println("Happy Birthday");
}

since the piece code will be use in a block there is no need to define as public/private/protected it will be scoped in a place between you lines of code whoever using the variable will have the acess of the method so we can omit the modifier.

lambdaHolderVariable = void greet(){
System.out.println("Happy Birthday");
}

Now the java 8 compiler is smart enough to look at the method body and tell what is actually the method is returning, likewise we know the body is returning any thing it is void, if it is returning any thing it will also be recognise by the compile. Therfore, the return type goes away.

lambdaHolderVariable = greet(){
System.out.println("Happy Birthday");
}

Now, as you can see we already have a variable that holds the name of the logic that contains inside the braces, therefore there is no need to define multiple names of a block of code, so let's change it and the color again.

lambdaHolderVariable = (){
System.out.println("Happy Birthday");
}

What has been added here in Java 8 is an expression that helps developers to easily recognise a lambda expression i.e. "->" and it is placed between empty brackets and starting curely brace. 

lambdaHolderVariable = () -> {
System.out.println("Happy Birthday");
}

Moreover, if there is only one line in your method body, you can actually omit the curely braces, but if you have more than one line you have to provide the braces. 

lambdaHolderVariable = () -> System.out.println("Happy Birthday");

That's your lambda expression.




References: javabrains.io

No comments:

Post a Comment