Groovy value types
The literal values in Groovy are similar to those in Java, but Groovy allows for generic variables that can hold any type and provides no enforcement and it allows you to declare variables with types and then enforce the type.
Declare variables with def
Declaring a varable using def allows for the flexibility most dynamic programming languges provide.
examples/groovy/variable_types_def.groovy
def x = 23 println x // 23 x = "hello" println x // hello x = 3.14 println x // 3.14 x = ["abc", "def"] println x // [abc, def] println x[0] // abc x = true println x // true
Declare variable as Integer
examples/groovy/variable_types_integer.groovy
Integer n = 19 println n // 19 n = 3.14 println n // 3 n = "world" // GroovyCastException // n = [2, 3] // GroovyCastException
If we declare a variable to be Integer it provides automatic casting from other numbers, but does not allow the assignment of other types. For example it will throw the following exception if we try to assign a string or a list:
Caught: org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'world' with class 'java.lang.String' to class 'java.lang.Integer' org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'world' with class 'java.lang.String' to class 'java.lang.Integer' at variable_types_integer.run(variable_types_integer.groovy:4)
byte
examples/groovy/variable_types_byte.groovy
byte b = 1 println b // 1 b = 127 println b // 127 b++ println b // -128 b = 200 println b // -56 b = 3.4 println b // 3 b = "hello" // GroovyCastException
Numbers
// primitive types byte b = 1 char c = 2 short s = 3 int i = 4 long l = 5 // infinite precision BigInteger bi = 6 // primitive types float f = 1.234 double d = 2.345 // infinite precision BigDecimal bd = 3.456
Boolean
We can declare a variable as boolean and then it can only hold true or false, but we can assign any type of value to it and it will be automatically converted to either true or false.
examples/groovy/variable_types_boolean.groovy
boolean b = false println b // false b = true println b // true b = 2 > 3 println b // false b = 2 println b // true b = 0 println b // false b = "abc" println b // true b = "" println b // false b = ["hello"] println b // true b = [] println b // false
Groovy Truth provides the details of the coercion to boolean values.
Syntax
See the Groovy syntax for more details.
Comments
boolean b = ""; returns false; however not b = "" even with prior declaration and assignment of b as boolean b = false per se within groovysh shell command prompt
Published on 2018-05-27