java 10 introduced the var
keyword. The var
keyword allows you to define and declare variables without data type. The compiler infers the type based on the type of the data assigned. var declaration is not allowed in a lambda expression.
Java11 supports the var keyword, used in a lambda expression with the JEP 323, Local-Variable Syntax
feature.
How to use the var keyword in lambda expression in java11?
Let’s see an example of lambda expressions
declare variables with type in a lambda expression
StringOperation str = (String first,String second) -> first + second;
Similarly, You can declare without type as given below
StringOperation str = (first, second) -> first + second;
interface StringOperation {
String concat(String first, String second);
}
public class java11 {
public static void main(String[] args) {
StringOperation str = (first, second) -> first + second;
String output = str.concat("Hello", " World");
System.out.println(output);
}
}
java10 introduced the var keyword for the local variable for type inference. If we use the var keyword in lambda expression with java10 versions given below, It throws
java: var syntax in implicit lambdas are not supported in -source 10 (use -source 11 or higher to enable var syntax in implicit lambdas)
StringOperation str = (var first,var second) -> first + second;
with java11, It supports lambda expression with the var keyword
interface StringOperation {
String concat(String first, String second);
}
public class java11 {
public static void main(String[] args) {
StringOperation str = (var first,var second) -> first + second;
String output = str.concat("Hello", " World");
System.out.println(output);
}
}
Java11 var keyword limitations:
In lambda expression, Either apply all parameters with var
or not.
(var first,var second) -> first + second; - valid and works (var first, second) -> first + second; - Invalid and throws following error
java: invalid lambda parameter declaration (cannot mix ‘var’ and implicitly-typed parameters)
You can not mix var with explicit types and the below code throws java: invalid lambda parameter declaration (cannot mix ‘var’ and explicitly-typed parameters)
(var first, String second) -> first + second;
We have to use parenthesis if a var keyword is used.