Using var in lambda expression parameters

Java Developer Certification Practice (For the complete list of practice questions in Java 11 and Java 17, referĀ https://talks.skilltoz.com/java-certification-exam-questions/

In this article, let us discuss the rules for using the var keyword in lambda expressions.

Can the var keyword be used for lambda expression parameters?

Yes, var can be used with lambda expression parameters starting from Java 11. For example, the below lambda expression has the parameters s1 and s2 declared using the var keyword.

(var s1, var s2) -> s1 + s2

However, the following rules are applicable.

There are a few limitations of using var in lambda.

  1. It is not allowed to use var for some parameters and skip for others.
(var s1, s2) -> s1 + s2  

The above does not compile as var is missing for s2.

2. It is not allowed to mix var with explicit types.

(var s1, String s2) -> s1 + s2

The above does not compile as var and String are used as parameters.

3. It is mandatory to use parenthesis () while using the var with the parameters.

var s1 -> s1.toLowerCase() 

The above does not compile as parenthesis is missing.

Reference

https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html

Leave a Reply

Your email address will not be published. Required fields are marked *