Variables in Groovy
In Groovy, variables are dynamically typed by default, but can also be explicitly declared. Here’s how you can work with variables in Groovy:
When you run this Groovy script, you’ll see:
In Groovy, variables are more flexible compared to statically typed languages:
The
def
keyword is used to declare variables, but it’s optional when assigning a value immediately.Groovy uses dynamic typing by default, so you don’t need to specify types explicitly. However, you can use type declarations if you want to.
Variables declared without initialization are
null
by default, not zero-valued like in some other languages.Groovy supports multiple assignment in a single line, as shown with variables
b
andc
.String interpolation is supported using double quotes and the
$
symbol, as demonstrated in the println statement forb
andc
.There’s no need for a special shorthand syntax like
:=
because Groovy’s variable declaration is already concise.
Remember, while Groovy allows for this flexibility, it’s often good practice to be explicit about your intentions, especially in larger codebases or when working in teams.