Hi all, my name is Hubert A. Klein Ikkink. Not a very common name, right? To make things easier I just picked the first letters of my firstname and surname and came up with haki. So there you have it, now I am also known as Mr. Haki or mrhaki for short. You can read more blog postings at www.mrhaki.com. I am a passionate Groovy and Java developer based in Tilburg, The Netherlands. My goal is to write clean, elegant, user-centered and high quality software. You can find me on Google+ and Twitter. Hubert is a DZone MVB and is not an employee of DZone and has posted 167 posts at DZone. You can read more from them at their website. View Full User Profile

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

10.12.2012
| 2556 views |
  • submit to reddit

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)

 

 

 

Published at DZone with permission of Hubert Klein Ikkink, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)