Java8 Nuggets - Type Inference

Overview

This is part II, in the series of “Java8 Nuggets” articles, that explicate how to introduce Java8 features in the codebase. This is mainly for me in case I need a quick reference in the future. So they are collected as listings from my personal notes taken from reading Oracle Java release blog.

Improved Type Inference

There are some nice syntactic improvements to Type Inference in Java 8.

  1. Target Type Inference
    List<String> stringList = new ArrayList<>();
    stringList.add("A");
    stringList.addAll(Arrays.asList());
    
    // results in compiler error in <= java 7 :
    
    // error: no suitable method found for 
    // addAll(List<Object>) ...
    // method List.addAll(Collection<? extends String>) is not applicable
    // (actual argument List<Object> cannot be converted
    // to Collection<? extends String> by method invocation conversion)
    
    // For it to compile, it needs to be modified as below
    
    List<String> stringList = new ArrayList<>();
    stringList.add("A");
    stringList
    .addAll(Arrays.<String>asList()); // <-- type witness
    
 
    
        // compiles without error in java8  
    
        List<String> stringList = new ArrayList<>();
            stringList.add("A");
            stringList.addAll(Arrays.asList());
            
          
    
 

Thats it!

Footnotes

1 code above is copyright of Oracle.