Lambdas must have a functional type and cannot be assigned to non-functional types like Object. Assigning a lambda to a variable of type Object will result in a compilation error. However, assigning a lambda to a variable of a functional interface type, such as Runnable, is correct. Lambdas can also be passed directly as arguments to methods, and the compiler will infer the type based on the context. The expected type of the lambda expression based on the context is called the Target Type. The Target Type allows the compiler to infer the type of the lambda expression and recognize that the same lambda can represent different functional interfaces. Method references also use the Target Type for inference, and the same method reference can adapt to different interfaces. The main difference between lambdas and method references is that method references make the inference stronger because the type is more explicit. Additionally, conversion between compatible functional interfaces is allowed. Understanding the Target Type is essential for working with lambdas and method references in Java.
dev.to
dev.to
Create attached notes ...
