concept def in category java

appears as: def
JavaFX in Action

This is an excerpt from Manning's book JavaFX in Action.

Listing 2.5. Declaring variables with def
Listing 2.5. Declaring variables with def

Using def instead of var results in variables that cannot be reassigned once created.

It’s tempting to think of def variables only as constants; indeed that’s how they’re often used, but it’s not always the case. A def variable cannot be reassigned, but the object it references can mutate (change its contents). Some types of objects are immutable (they provide no way to change their content once created, examples being String and Integer), so we might assume a def variable of an immutable type must be a constant. But again, this is not always the case. In a later section we’ll investigate bound variables, revisiting def to see how a variable (even of an immutable type) can change its value without actually changing its content.

So, ignoring bound variables for the moment, a valid question is “when should we use var and when should we use def?” First, def is useful if we want to drop hints to fellow programmers as to how a given variable should be used. Second, the compiler can detect misuse of a variable if it knows how we intend to use it, but crucially, JFX can better optimize our software if given extra information about the data it’s working with.

For simple assignments like those in listing 2.5, it’s largely a matter of choice or style. Using def helps make our intentions clear and means our code might run a shade faster.

Value types are created using the var or the def keyword, followed by the variable’s name and optionally a colon and a type.

def ship2 = new SpaceShip();
ship2.name="The Liberator";
ship2.crew=7;
ship2.canTimeTravel=false;
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest