Better Type Inference in Java 8 Generics

Java 7 gave us the diamond operator:

  Map<String, String> dict = new HashMap<>();

The code above doesn’t duplicate the type parameters unnecessarily as it made perfect sense to extend type inference to instantiation. Now Java 8 pushes type inference a little further.

Let’s say we have a simple utility class with a single public method that takes a Map<String, String> as parameter and returns its size (I know it is not a useful utility method but please bear with me as this is only to demonstrate the point in question).

package yagizerkan.sandbox.java8.generics;

public class TypeInference {
  public int getDictionarySize(Map<String, String> theDict) {
    return theDict.size();
  }
}

Now let’s write two tests for this method. Both are going to test the size of an empty dictionary. The first one is going to do it by instantiating a dictionary and assigning it to a local variable:

  @Test
  public void emptyDictionarySizeShouldBeZero() {
    TypeInference testObj = new TypeInference();

    Map<String, String> dict = new HashMap<>();

    int expected = 0;
    int actual = testObj.getDictionarySize(dict);

    assertEquals("Size is incorrect!", expected, actual);
  }

Nothing surprising above. The diamond operator works like a charm with the Java 7 compiler. However the same compiler doesn’t like the second test very much:

  @Test
  public void emptyDictionarySizeShouldBeZero2() {
    TypeInference testObj = new TypeInference();

    int expected = 0;
    int actual = testObj.getDictionarySize(new HashMap<>());  //Java 7: Compile Error.
                                                              //Java 8: Better Type Inference

    assertEquals("Size is incorrect!", expected, actual);
  }

This is where Java 8 improves type inference. It is now possible to infer the generic types from method signatures when passing a constructor as the parameter of a method.

Source Code

You can find the source code on my GitHub repository.

, , ,

  1. Leave a comment

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: