Groovy Variable Types: Dynamic and Static Distinguish

Variables in Groovy can be categorized into two types: dynamic type and static type. The type of a dynamic type variable is determined at runtime, whereas the type of a static type variable is determined at compile time.

In Groovy, you can use the def keyword to define a dynamic type variable, for example:

// Define dynamic type variables
def name = "John"
def age = 30

In the example above, both name and age are dynamic type variables. Their types are determined at runtime. This means that any value of any type can be assigned to these variables, such as strings, integers, floating-point numbers, collections, and so on.

Besides the def keyword, Groovy also supports using keywords to define static type variables. The type of a static type variable is determined at compile time, which can improve program performance.

For example, you can use the String keyword to define a statically typed string variable:

// Define a statically typed string variable
String name = "John"

In the example above, name is a statically typed string variable. Its type is determined as String at compile time. This means that only values of the string type can be assigned to this variable; values of other types cannot be assigned to it.