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.
1 2 3 4 5 6 7 8 9 10 11 12 | ... private static void demoMethod(Person person, Function<Person, Person> function) { Person rtn = function.apply(person); System.out.println("param person instanceof Person? " + (rtn instanceof Person)); System.out.println("param person instanceof Student? " + (rtn instanceof Student)); System.out.println("rtn instanceof Person? " + (rtn instanceof Person)); System.out.println("rtn instanceof Student? " + (rtn instanceof Student)); } ... |
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.
1 2 3 4 5 6 7 8 9 | class Person { } class Student extends Person { } |
Now Polymorphism allows us to pass or/and return Student objects instead of Person objects.
1 2 3 4 5 6 7 | ... public static void main(String[] args) { demoMethod(new Person(), (str) -> new Person()); demoMethod(new Student(), (str) -> new Student()); } ... |
The codes output
1 2 3 4 5 6 7 8 | param person instanceof Person?true param person instanceof Student?false rtn instanceof Person?true rtn instanceof Student?false param person instanceof Person?true param person instanceof Student?true rtn instanceof Person?true rtn instanceof Student?true |
But…
When we assign a Lambda expression to a variable, we need to declare that variable using Generics.
1 2 3 4 | ... Function<Student, Student> function = (str) -> new Student(); demoMethod(new Student(), function); ... |
This results in a compilation error.
Because
1 2 3 | The method demoMethod(Person, Function<Person,Person>) in the type LambdaExpressionParamAndReturnTypes is not applicable for the arguments (Student, Function<Student,Student>) |
The Full Codes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import java.util.function.Function; public class LambdaExpressionParamAndReturnTypes { public static void main(String[] args) { demoMethod(new Person(), (str) -> new Person()); demoMethod(new Student(), (str) -> new Student()); } private static void demoMethod(Person person, Function<Person, Person> function) { Person rtn = function.apply(person); System.out.println("param person instanceof Person? " + (rtn instanceof Person)); System.out.println("param person instanceof Student? " + (rtn instanceof Student)); System.out.println("rtn instanceof Person? " + (rtn instanceof Person)); System.out.println("rtn instanceof Student? " + (rtn instanceof Student)); } } class Person { } class Student extends Person { } |