Groovy – The concept of optional typing

We haven’t used any explicit static typing in the way that you’re familiar with in Java. We assigned strings and numbers to variables and didn’t care about the type. Besides this, Groovy implicitly assumes these variables to be of static type java.lang.Object.

Assigning Types:

Groovy offers the choice of assigning types explicitly just as you do in Java. Given table gives examples of optional static type declarations and the dynamic type used at runtime. The def keyword is used to indicate that no particular type is demanded.

Statement

Type of Value

Comment

def a = 1

java.lang.Integer

Implicit typing

def b = 1.0f

java.lang.Float

int c = 1

java.lang.Integer

Explicit typing using the Java primitive

type names

float d = 1

java.lang.Float

Integer e = 1

java.lang.Integer

Explicit typing using reference type names

String f = ‘1’

java.lang.String

It doesn’t matter whether you declare or cast a variable to be of type int or Integer. Groovy uses the reference type (Integer). If you prefer to be concise, and you believe your code’s readers understand Groovy well enough, use int. If you want to be explicit, or you wish to highlight to Groovy newcomers that you really are using objects, use Integer.

It is important to understand that regardless of whether a variable’s type is explicitly declared, the system is type safe. Unlike untyped languages, Groovy doesn’t allow you to treat an object of one type as an instance of a different type without a well-defined conversion being available.

Static versus dynamic typing

The choice between static and dynamic typing is one of the key benefits of Groovy.

Static typing provides more information for optimization, more sanity checks at compile time, and better IDE support; it also reveals additional information about the meaning of variables or method parameters and allows method over-loading. Static typing is also a prerequisite for getting meaningful information from reflection.

Dynamic typing, on the other hand, is not only convenient for the lazy programmer, but also useful for relaying and duck typing. Suppose you get an object as the result of a method call, and you have to relay it as an argument to some other method call without doing anything with that object yourself:

def node = document.findMyNode()

log.info node

db.store node

The usage of dynamic typing is calling methods on objects that have no guaranteed type. This is often called duck typing.

For programmers with a strong Java background, it is not uncommon to start programming Groovy almost entirely using static types, and gradually shift into a more dynamic mode over time. This is legitimate because it allows everybody to use what they are confident with.

Leave A Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.