Software Development

Java Lambda Expression Parameter and Return Types

java Sort Enum Properties Monitor Directory File Lambda Expression parameter return types Validate XML String XSD ExecutorService AutoCloseable Try-With-Resources

This post shows how to pass the type of parameters to and return from a Lambda expression in Java based on the functional interface abstract method definition.  The types must be sub-types or exact match to those defined in the abstract method for the parameters and return type.

Using the Function Interface And Lambda Expression

Consider the following method.

It accepts a Person object and a Function functional interface that accepts and returns a Person object.

Person class and its sub-class

The Student class extends the Person class.

Now Polymorphism allows us to pass or/and return Student objects instead of Person objects.

The codes output

But…

When we assign a Lambda expression to a variable, we need to declare that variable using Generics.

This results in a compilation error.

Because

The Full Codes

 

You Might Also Like