var in java 10

In my Java 10/11 talk, I ask the audience if this code compiles:

var var = "var";

I usually get about a 50/50 response. The answer is that it does compile due to backward compatibility. You could have a local variable named var and it should still work. When I gave the talk at the NY Java Sig tonight, Mark asked “what if you have a class named lower case var”. After wincing a bit at the lower case class name, I said I didn’t know. But I definitely wanted to find out.

The answer is actually pretty interesting – it depends on what version of Java you compile with!

Compiling var.java

Fierst I created a class


public class var {

  public static final String STR = "a";

}

This class compiles in Java 9 and below. It does not compile in Java 10 or 11. Instead you get the message:

as of release 10, 'var' is a restricted local variable type and cannot be used for type declarations

This means that you have to change the class name. However, you can still have a var.class file compiled in Java 9 or below.

Referencing that var.class file

Compiling OR running the code with Java 10/11 doesn’t let you refer to that var.class file either.

TripleVar.java:5: error: illegal reference to restricted type 'var'

Conclusion

If you followed bad practices and named your class var.class, you must change it. Even if you compiled in Java 9, it will not run in Java 10.

2 thoughts on “var in java 10

  1. Nice. Not too surprising, since hardly anyone uses lowercase class names and supporting this would make things way more complicated. (It would probably mean that if such a class is in scope, than type inference doesn’t work for that scope.)

    On the other hand, var is a perfectly reasonable name for a package. Luckily that’s not ambiguous so it probably works.

  2. Who would ever name a class “var” anyway? Project Lombok, that’s who:

    https://projectlombok.org/

    This has apparently caused a few people some annoyance recently 🙂

    https://github.com/rzwitserloot/lombok/issues/1676

    Seriously though, Lombok seems great. Where else do you get things like this:

    https://projectlombok.org/features/val
    and many more
    https://projectlombok.org/features/all
    and even more
    https://projectlombok.org/features/experimental/all

    In case you’re wondering how it works: magic:
    http://jnb.ociweb.com/jnb/jnbJan2010.html#controversy

Leave a Reply

Your email address will not be published. Required fields are marked *