Skip to content
AgileLogics
5 min read

Data Types

Prerequisites: Variables and def

Every value in Groovy is an object with a class — even numbers. Groovy uses Java's types and adds a few conveniences on top.

println 42.getClass().name
println 3.14.getClass().name
println 'text'.getClass().name
println "sum: ${1 + 1}".getClass().name
println true.getClass().name
println ([1, 2].getClass().name)
println ([a: 1].getClass().name)
println ((1..3).getClass().name)
println ({ it }.getClass().superclass.name)
java.lang.Integer
java.math.BigDecimal
java.lang.String
org.codehaus.groovy.runtime.GStringImpl
java.lang.Boolean
java.util.ArrayList
java.util.LinkedHashMap
groovy.lang.IntRange
groovy.lang.Closure
Literal Type
42 Integer (grows to Long or BigInteger if too big)
3.14 BigDecimal — exact decimal, not double
'text' String
"sum: ${...}" GString (a string with placeholders)
true / false Boolean
[1, 2] ArrayList
[a: 1] LinkedHashMap (keeps insertion order)
1..3 IntRange
{ it } Closure
null no object at all

Checking types

def value = 42
println value instanceof Integer
println value instanceof Number
println value in Number        // "in" also checks class membership

def nothing = null
println nothing == null
println nothing?.getClass()    // ?. avoids calling a method on null
true
true
true
true
null

Converting between types

println '42' as int
println '42'.toInteger() + 1
println '3.5'.toBigDecimal() * 2
println 42.toString() + '!'
println 65 as char
println 'yes'.isNumber()
42
43
7.0
42!
A
false

as converts ("coerces") a value to a type; toInteger(), toBigDecimal(), and friends are Groovy's additions to String. isNumber() checks first, which is useful for user input.

Primitives

You can declare Java primitives (int, double, boolean, ...), and Groovy boxes them into objects when needed. In dynamic code the difference rarely matters; with static compilation, primitives are faster.