Type Inference at Design Time via Eclipse

August 17, 2009 | 2 min Read

Dynamically typed programming languages have become more popular over the recent years. Dynamic typing makes certain tasks a lot easier, however, I will not go into a full discussion of dynamic versus static typed languages (I’m saving that discussion for later). Instead, I want to take a look at one of the cool ideas in dynamic language design and demonstrate how Eclipse can somewhat emulate it.

By definition, dynamic languages have no concept of variable types. This means there is no need for a type declaration… so for example, in Python or Ruby you can just write:


Some statically typed languages also allow the type declaration of variables to be omitted. But since the language is statically typed, where the does the variable type come from? A reasonably smart compiler can infer the type of a variable by looking at how the variable is used. Haskell and Scala are two examples of such languages that allow implicit typing and then determine the types through compile time type inference. This allows you to write the following scala code:

var randomNumber=new BigDecimal(4)

The type of randomNumber is java.math.BigDecimal. This avoids having to type BigDecimal twice… once for the variable type declaration and once for the constructor. Since Eclipse has a full blown Java compiler under the hood (a fairly smart one), it allows you to do almost the same. You can basically omit the type declaration altogether, and when Eclipse complains just, hit Ctrl+1 and select the appropriate option. The official name for that shortcut is Quickfix, but I like to think of as: “Dear Eclipse, I’m just too lazy, why don’t you fix it for me?”

I don’t know whether this quickfix was created with this usage pattern in mind, but I find myself using this quite often. A close relative is the Extract variable refactoring which also does design time type inference. Another refactoring where type inference comes into play is Generalize declared type, which lets you reduce the specificness of a variable type to its lowest common denominator.

I am sure there are a number of similar refactorings and quick fixes. These powerful features demonstrate how a smart IDE can make working with a statically typed language much easier, while still reaping the benefits of static type checks.

What are your favorite type inference shortcuts?