Wednesday, May 14, 2008

Type inference thoughts

I have been wondering about one thing and throw out this question just in case someone possibly reads my blog - does type inference bring any benefits apart from less typing?

I know proponents of dynamic typing consider declaring variable types "noise" because it is the antithesis of their style of coding, and they say the compiler can usually infer the type for you anyway. Scala for instance is designed this way:

var x = "Hello"

The compiler will infer that x is of type String. You can reassign it (just like you can in Java) to a new String, but if you try to reassign an object which is not a String compile will fail.

Map<Integer, Office> offMap = ....
for instance, is more to type, that is true. In my opinion that can be an acceptable tradeoff. If I have the code in an IDE mouseover could tell me the return type of the right hand side method, true, but I often look at code through other interfaces than an IDE (online, books, a shell). Note that I'm not saying I think type inference is bad... sometimes it is a relief. But I don't think it is terrible that Java lacks it, either. For me it is just a matter of style.

But just in case I have missed anything, my question is again: does type inference bring any other possible benefits? Compiler optimization...?