What is a casting expression in Java?


A cast expression provides a mechanism to explicitly provide a lambda expression's type if none can be conveniently inferred from context. It is also useful to resolve ambiguity when a method declaration is overloaded with unrelated functional interface types.

Syntax

Object o = () -> { System.out.println("TutorialsPoint"); };
// Illegal:
Object o = (Runnable) () -> { System.out.println("TutorialsPoint"); }; // Legal

Example

interface Algebra1 {
   int operate(int a, int b);
}
interface Algebra2 {
   int operate(int a, int b);
}
public class LambdaCastingTest {
   public static void main(String[] args) {
      printResult((Algebra1)(a, b) -> a + b);  // Cast Expression in Lambda
      printResult((Algebra2)(a, b) -> a * b); // Cast Expression in Lambda
   }
   static void printResult(Algebra1 a) {
      System.out.println("From Algebra1 Interface: " + a.operate(40, 20));
   }
   static void printResult(Algebra2 a) {
      System.out.println("From Algebra2 Interface: " + a.operate(40, 20));
   }
}

Output

From Algebra1 Interface: 60
From Algebra2 Interface: 800

Updated on: 11-Jul-2020

516 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements