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 Convert LocalDateTime OffsetDateTime Run Codes Before Shutdown XML Tag Lambda PostgreSQL JDBC invoke JavaScript Applet SFTP Batch hang block main thread MySQL JDBC try-with-resources delete Unencrypted SoapFault Apache CXF Remove XML Element XSLT skip execute finally public static void main constructor fields Eclipse convert Iterator Stream StreamSupport XMLEncoder XMLDecoder rename P6Spy JDBC Example PDF Version JasperReports Run from Ant iReport Page Numbers Count entities persistence context hibernate

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

 

Got comments, or suggestions? Please visit our Facebook page!

You Might Also Like