Background
In last post we say what is Lambda expression and how we can use it. In this post we will see some advance topics related to Lambda expression like -
- Generic Functional Interfaces
- Passing Lambda expressions as method arguments
- Exception handling in Lambda expressions
Generic Functional Interfaces
lambda expression themselves cannot have generics but the functional interface that corresponds to a lambda expression can have generics.
Consider following demo code-
Consider following demo code-
public class HelloWorld { public static void main(String args[]) { MyInterface<String> myStringInterface = (input) -> "Hello " + input; MyInterface<Integer> myIntInterface = (input) -> 10 + input; System.out.println("String based lambda exp : " + myStringInterface.myFunc("OSFG")); System.out.println("Integer based labmda exp : " + myIntInterface.myFunc(14)); } } interface MyInterface<T> { T myFunc(T t); }
And the output is -
String based lambda exp : Hello OSFG
Integer based labmda exp : 24
Notice how same method is made generic to operate on both String and Integer inputs.
Passing Lambda expressions as method arguments
Lambda expressions can be sent as method arguments. This makes Java more powerful as you can now send executable code as a part of method argument. Consider following demo code -
public class HelloWorld { public static void main(String args[]) { System.out.println("Welcome Lambda : " + executeMyFunc((input)-> "Welcome " + input,"OSFG")); System.out.println("Hello Lamda : " + executeMyFunc((input)-> "Hello " + input,"OSFG")); } public static String executeMyFunc(MyInterface myInterface, String input) { return myInterface.myFunc(input); } } interface MyInterface { String myFunc(String t); }
and the output is -
Welcome Lambda : Welcome OSFG
Hello Lamda : Hello OSFG
Hello Lamda : Hello OSFG
Exception handling in Lambda expressions
A lambda expression can throw an exception just like any other method. However if that exception is a checked exception then it should be compatible with the exceptions listed in the throws clause of the abstract method in the corresponding functional interface.
Consider following demo code -
public class HelloWorld { public static void main(String args[]) throws MyException { MyInterface myInterface = (input) -> { if(input == null) { throw new MyException(); } return "Hello World"; }; } } interface MyInterface { String myFunc(String t) throws MyException; } class MyException extends Exception { public MyException() { super("MyException"); } }
NOTE : Here if you abstract method does not throw the checked exception code will fail to compile.
That's it. Let me know if you have any questions on Lambda expressions.