Aspects

Java 8 Onwards

Functional Programming

Streams

Useful Resources

Functional Programming - Type Inference



Type inference is a technique by which a compiler automatically deduces the type of a parameter passed or of return type of a method. Java 8 onwards, Lambda expression uses type inference prominently.

See the examples below for clarification on type inference.

Example - Type Inference of Integers

FunctionTester.java

package com.tutorialspoint;

public class FunctionTester {

   public static void main(String[] args) {
      Join<Integer,Integer,Integer> sum = (a,b) ->  a + b;
      System.out.println(sum.compute(10,20));
   }

   interface Join<K,V,R>{
      R compute(K k ,V v);
   }
}

Output

Run the FunctionTester and verify the output.

30

Example - Type Inference of Strings

FunctionTester.java

package com.tutorialspoint;

public class FunctionTester {

   public static void main(String[] args) {
      Join<String, String, String> concat = (a,b) ->  a + b;
      System.out.println(concat.compute("Hello ","World!"));
   }

   interface Join<K,V,R>{
      R compute(K k ,V v);
   }
}

Output

Run the FunctionTester and verify the output.

Hello World!

A lambda expression treats each parameter and its return type as Object initially and then inferred the data type accordingly. In first case, the type inferred is Integer and in second case type inferred is String.

Advertisements