Java 10 introduced local type inference, which is really cool:
var list = new ArrayList<String>(); // Compiles fine
However, it appears people are reluctant to update their Java versions the day (week, month, year) a new release is out.
This means that I need to wait till the EOL of Java 8 before I can even use List.of(1, 2, 3)
if want to support the majority of users using old Java versions.
Local type inference on the other hand, would likely be inferred when it is compiled to bytecode, so presumably programs using it would likely run on older Java versions (9 or 8). On the other hand, Java seems to like doing optimizations at runtime, which could mean that type-inference requires JRE version 10.
Has anyone tried this out? Do programs using type inference run on older Java versions?
Your input is appreciated.
The type inference doesn’t change the bytecode, so in principle, compiled code using var
would be compatible with older JVMs.
However, like always, javac
doesn’t allow you to combine the -source
option with a higher release version than the -target
option.
So, the only way to use var
in source code, to run with an older version, would be compiling it for Java 10, followed by downporting the compiled classes to an earlier version. The simplest approach would be just changing the class file version. I just verified that a simple test case using var
worked on Java 9 after decrementing the class version number. But, of course, a more sophisticated downporting tool should verify that no other code features or API references of the newer platform features slipped through.
Perhaps, an alternative compiler will show up, allowing the flexibility to use a newer source version with an older target version. As said at the beginning, javac
never did this.