Hi all,
While studying for the OCP exam, I noticed that Java 11 allows using var for lambda parameters. I’m a bit confused about how this affects type inference and annotations.
For example, in a lambda like (var x, var y) -> x + y, does using var change anything in terms of type safety or compilation compared to explicitly specifying the parameter types? Also, are there any scenarios in the exam where using var in lambdas could lead to a tricky question?
Retro Bowl
Would really appreciate a clear explanation or example.
Thanks!
Behavior of var with Lambda Parameters in Java 11+ for OCP
Moderator: admin
-
RoseBL
- Posts: 1
- Joined: Tue Jul 15, 2025 10:18 pm
- Contact:
-
admin
- Site Admin
- Posts: 10444
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: Behavior of var with Lambda Parameters in Java 11+ for OCP
No, there is no issue with type safety here because the compiler will deduce the type of var from the functional method parameters of the interface that the lambda is trying to implement.
In case of (var x, var y) -> x + y, you have to see the context where this expression is used. That will determine the functional method and thus the types of both the vars
In case of (var x, var y) -> x + y, you have to see the context where this expression is used. That will determine the functional method and thus the types of both the vars
Who is online
Users browsing this forum: Google [Bot] and 38 guests