Loading...

Wednesday, October 3, 2012

Groovy Goodness: Using Project Coin Features Also With Older Java Versions

Since Groovy 2 we can use a subset of the Project Coin features from Java 7. But we don't have to run Java 7 to use them in Groovy code. We can use the new features even if we run our Groovy code on older Java versions.

Groovy didn't have to add all Project Coin features, because some are already supported in Groovy, like the switch statement on String objects or diamond operator. A feature that is added is a syntax enhancement to define binary literals. We can now use binary integral literals by prefixing the value with 0b:

// Binary notation.
int x = 0b101
assert x == 5

The underscore in number literals is now supported in Groovy. We can define numbers and use an underscore to make them more readable. The value is not changed:

import static java.text.NumberFormat.getInstance as formatter
import static java.util.Locale.US

// Use underscore for number literals.
double d = 89_192.29
assert formatter(US).format(d) == '89,192.29'

long longNumber = 1230_3910_1929_182931
assert longNumber == 123039101929182931

int length = 5_10
assert length == 510

long hex = 0x00_ff
assert hex == 255

We can define a multi-catch exception in Groovy 2. We specify more than exception in the catch clause separated by a pipe (|) symbol:

import java.lang.reflect.*

// Multicatch.
@groovy.transform.ToString
class Person {
    String name
}

try {
    final Person p = new Person(name: 'mrhaki')
    final Method toString = p.class.getMethod("toString1", null)
    final Object result = toString.invoke(p, null)
} catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
    assert e
}

(Code written with Groovy 2.0.4)

0 comments:

Post a Comment