Type Inference and Type Witness

What is Type Inference in java?

Type inference is a Java compiler’s ability to look at each method invocation and corresponding declaration to determine the type argument (or arguments) that make the invocation applicable.

List<String> list1 = new ArrayList<>();

In the above example, ArrayList<> the diamond operator is empty but during compilation java automatically determines the Type as String using Type inference.Note this functionality is only available after java 1.7

What is Type Witness in java?

You can stop compiler from automatically inference and ask the compiler to take a specific type while calling a method, that is called type inference

ClassName.<Type>.methodCall(type_reference);
package com.test;

import java.util.ArrayList;
import java.util.List;

public class App {
	public static <T> void addToList(T t,List<Bucket<T>> list){
		Bucket<T> bucket = new Bucket<>();
		bucket.setItem(t);
		list.add(bucket);
		System.out.println(t.toString()+" has been added to the list");
	}
	public static void main(String[] args) {
		//Type Inference
		//on Right Side ArrayList has empty diamond operator, it is automatically inference
		List<Bucket<Integer>> list = new ArrayList<>();
		//Type Witness
		//Ask Compiler to consider the T as passed in the diamond operator
		App.<Integer>addToList(10,list);
	}
}
class Bucket<T>{
	private T item;

	public T getItem() {
		return item;
	}

	public void setItem(T item) {
		this.item = item;
	}
}

Leave a Comment