Brian Slesinsky's Weblog

Saturday, 25 Mar 2006

Why Aren't There Auto Variables In Java?

Type inference is finally getting into mainstream languages. The next version of the C++ standard will very likely allow you to do this:

  auto foo = compute_foo();

The auto keyword indicates that foo is a local variable whose type is automatically inferred from the type of the expression on the right side of the equal sign, in this case compute_foo()'s return type.

This will also be in C# 3.0, except with a different keyword:

  var s = "Hello";

(For the search engines, this is called "implicitly typed local variables" in C-sharp-land.)

There's no reason why Java shouldn't do it too, but where is the JSR?

There were some closed bugs on this (4459053 and 6242254) but I think it's time to try again. I opened an RFE in Sun's bug database and I'll link to it as soon as it appears.

While waiting for a new Java version, maybe there's something else we could do. Suppose your favorite IDE had an option to hide the types of local variables and display "auto" instead? The IDE could do the type inference and add the proper type to the source code when you compile.

Doing it in the IDE might seem a little scary because the editor isn't showing you the real source code. But it could also display the variable's type on demand (perhaps via mouse hover), so it's not all that different from hiding import statements or other forms of code folding. I think we'd quickly get used to this feature and wonder how we lived without it. Even after it makes it into the language, it still might be nice to read old source code using the new syntax without actually having to convert it.

If you use IntelliJ and like this idea, you can vote for it in IntelliJ's bug database. If someone wants to open an issue for this for some another IDE, let me know and I'll link to it.

[Alas, it looks like this won't happen. See my update.]