Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 4

[ 63 ]

For all intents and purposes, you can treat any numeric value as if it is both an
object-based numeric value and a primitive. You can pass a Groovy numeric object to
a Java method that requires a primitive, and Groovy automatically unboxes it to the
equivalent primitive.


If we need to explicitly coerce a numeric type to its equivalent primitive, for example,
to call a Java method that takes a primitive parameter, we can do this unboxing with
the (as) operator:


javaMethodCall(3.0 as double))

In most cases, this is redundant as Groovy will automatically unbox to the correct
type. However, it can be useful as a hint about which method call we need to select
when multiple methods signatures exist.


Strings


Regular Groovy strings can be defined with either the single quote (') or double
quotes ("") characters. This makes it easy to include either type of quotes in a
string literal:


String singleQuote = "A 'single' quoted String"
String doubleQuote = 'A "double" quoted String'

Strings declared with double quotes can also include arbitrary expressions by using
the ${expression} syntax. Any valid Groovy expression can be included in the
${..}. Normal strings in Groovy are instances of the java.lang.String class.
Strings that contain the ${...} syntax are instantiated as Groovy GString objects:


given: "a Groovy object"
Customer customer = new Customer(name:"Daniel Dewdney")
def string1 = "Customer name is Daniel Dewdney"
def string2 = "Customer name is ${customer.name}"
expect: "We can compare both strings as if the are equivalent"
string1 == string2
and: "they are implemented by two different classes"
string1 instanceof String
string2 instanceof GString

Multiline strings can be defined by surrounding them in a triple quote, which can
use single quote (''') or double quote (""") characters as follows:


given: "some multiline strings with single and double quotes"
String multiLine = '''Line one
Line two
Free download pdf