DEV Community

koji
koji

Posted on

Apache Groovy with Java 7 and 8 syntaxs

Since Apache Groovy 2.6(latest vesrion is 2.6.0-alpha-2 at 2017-Nov-16) it can use Lambda syntax from Java8 and try-with-resources from Java7.
Groovist uses alreday like these functions.(Closure)
But adapting to Java's syntax is really important to reach Java Developer who doesn't use yet Apache Groovy.

Install Apache Groovy, then change file name from Foo.java to Foo.groovy and execute simply groovy Foo.groovy.
Java Developer equals Apache Groovy Developer again since Apache Groovy 2.6.

But this functions are not yet standard on Apache Groovy.
Apache Groovy 2.6 supports optionally, Apache Groovy 3 support as default.
Apache Groovy 2.6 is yet alpha phase. but it is allready out. we can test it!

Install Apache Groovy 2.6

Install via sdkman.
Apache Groovy 2.6 is not yet support Java8 syntax as default
It have to be specified an option -Dgroovy.antlr4=true by execute groovy.

[koji:~]$ sdk install groovy 2.6.0-alpha-2 
[koji:~]$ sdk use groovy 2.6.0-alpha-2

# to activate Java7/9 syntax.
[koji:~]$ groovyConsole -Dgroovy.antlr4=true&


# of course you can JAVA_OPTS.
[koji:~]$ echo $JAVA_OPTS

[koji:~]$ export JAVA_OPTS="-Dgroovy.antlr4=true"
[koji:~]$ echo $JAVA_OPTS
-Dgroovy.antlr4=true
[koji:~]$ groovyConsole&

Enter fullscreen mode Exit fullscreen mode

try-with-resources

def file = new File("/tmp/test.txt")

/*
def fileReader = file.newReader()
println fileReader.ready()
fileReader.close()
println fileReader.ready() // java.io.IOException: Stream closed. of ocurse :)
*/

// try-with-resources ! Since Apache Groovy 2.6 can use!
try(BufferedReader br = file.newReader()) {
    br.eachLine {
        println it
    }
} catch(Exception e) {
    println e
}

// Normal Groovy way!
file.withReader {BufferedReader br ->
    br.eachLine {
        println it
    }
}

Enter fullscreen mode Exit fullscreen mode

Use Lambda

// Lamda syntax is available!
java.util.function.Function<Integer, String> test = (i) -> {"${i} !?"}
assert "123 !?" == test.apply(123)

// Lambda with streams.
List<Integer> list = [1,2,3,4,5]
assert [10, 8, 6, 4, 2] == list.stream().map((a) -> {a * 2}).sorted((a, b) -> { return b - a; }).collect()

// Normal Groovy way!
assert [10, 8, 6, 4, 2] == list.collect{it * 2}.sort{a,b -> b <=> a}
Enter fullscreen mode Exit fullscreen mode

I like Groovy style more than Java.
But this new syntax parser is really helpfull for Java Developer learning Apache Groovy.

Top comments (0)