Local Variable Type Inference in Java10

March 22 2018

It is going to be probably harder to keep in touch with all the Java VM releases so here is a short post showing the main change in Java10, Local Variable Type Inference.

Now it is possible to use var as the declaring type of an Object. This has been there in Scala and other JVM languages for sometimes, and is something the java compiler now handles. This does not change anything in the underlying bytecode, and types are still enforced.

Below is a slighty updated sample from the Oracle website on how to use var. The snippet below opens a connection to a website and read the content of the whole page using Java8’s Collectors.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
import java.net.URL;
import static java.lang.System.*;

public class HelloTen {
	public static void main(String[] args) throws Exception {
		var url = new URL(args[0]); 
		var conn = url.openConnection(); 
		var buffer = 
			new BufferedReader(
				new InputStreamReader(conn.getInputStream()));
		var text = buffer.lines().collect(Collectors.joining());

The code is now de-cluttered from all the different types, URL, Connection, etc… which can all be infered by the compiler.

A second example that I find pretty neat is how to construct dynamic objects. For some time now you could actually create a dynamic object and call its methods on the fly like the below:

(new Object() {
	public void hello() {
		out.println("hello dynamic object!");

Unfortunately, once you started and try to reference the object things, were getting slightly more complicated, and the code below does not compile …

Object o = new Object() {
	public void hello() {
		out.println("hello dynamic object!");


You get the obvious method not found compilation error below, since the hello() method is obviously not part of the generic Object type.

HelloTen.java:17: error: cannot find symbol
  symbol:   method hello()
  location: variable o of type Object
1 error

var now allows you to define and reference a new object and its inlined methods as well as actually call them. Yes, the type is inferred properly by the compiler.

var o = new Object() {
	public void hello() {
		out.println("hello dynamic object!");

Behind close doors, the java10 compiler creates an inner class HelloTen$1, with the defined hello method.

#2 = Class              #17            // HelloTen$1
#3 = Methodref          #2.#16         // HelloTen$1."<init>":()V
#4 = Methodref          #2.#18         // HelloTen$1.hello:()V

And running the code, outputs the output from the hello method:

hello dynamic object!

Built with Hugo

© Nicolas Modrzyk 2017 - hellonico @ gmail dot com