Question
Why can’t I assign a lambda expression to a variable declared with the var keyword in Java?
var foo = "boo"; // This is valid
var predicateVar = apple -> apple.getColor().equals("red"); // This is invalid
Answer
In Java, the var keyword introduced in Java 10 allows for local variable type inference, enabling developers to declare variables without explicitly defining their types. However, lambda expressions pose a unique challenge because their types cannot be inferred as they are in many cases, unlike primitive types or object types like String or ArrayList.
// Example of assigning a lambda to a variable with an explicit type
Predicate<Apple> predicateVar = apple -> apple.getColor().equals("red");
Causes
- Lambda expressions do not have a distinct type that can be inferred; they are functional interfaces and require an explicit target type for proper identification.
- The JVM needs to know the expected interface type for the lambda; without a specific declaration, it cannot deduce the necessary type for interfaces contextually associated with lambdas.
Solutions
- To declare a variable for a lambda expression, explicitly specify the functional interface type, like so: ```java Function<Apple, Boolean> predicateVar = apple -> apple.getColor().equals("red"); ```
- If you use collections that accept lambdas (like List's forEach), instead set it into a context where the type can be inferred alongside the appropriate generics.
Common Mistakes
Mistake: Declaring a lambda expression without specifying a target functional interface type.
Solution: Always specify the target type when working with lambda expressions.
Mistake: Assuming that var can be used for all kinds of assignments without limitations.
Solution: Understand that var is constrained by the type inference rules of Java, particularly with lambdas requiring functional interfaces.
Helpers
- Java var keyword
- lambda expression
- Java type inference
- Java functional interfaces
- Java 10 features