Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with this Groovy construct?

Tags:

groovy

This is a short Groovy script:

import org.apache.commons.io.FileUtils;
def dir = new File("/mydir")
def files = FileUtils.listFiles(dir, new String[] { "java" }, false)

It says:

No expression for the array constructor call at line: 2

What's wrong?

like image 592
yegor256 Avatar asked Feb 22 '11 12:02

yegor256


People also ask

What is Groovy constructor?

Groovy adds the constructor automatically in the generated class. We can use named arguments to create an instance of a POGO, because of the Map argument constructor. This only works if we don't add our own constructor and the properties are not final. Since Groovy 2.5.

What is this in Groovy?

" this " in a block mean in Groovy always (be it a normal Java-like block or a Closure) the surrounding class (instance). " owner " is a property of the Closure and points to the embedding object, which is either a class (instance), and then then same as " this ", or another Closure.

What does [:] mean in Groovy?

[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]

How do you call a method in Groovy?

In Groovy we can add a method named call to a class and then invoke the method without using the name call . We would simply just type the parentheses and optional arguments on an object instance. Groovy calls this the call operator: () . This can be especially useful in for example a DSL written with Groovy.


1 Answers

The call should be:

def files = FileUtils.listFiles(dir, [ "java" ] as String[], false)

Groovy uses Lists by default, and the as operator can be used to coerce these lists into arrays of a specified type (often for interacting with the java api as in this example)

[edit]

As an aside, you can do this with pure Groovy like so:

def files = dir.listFiles().findAll { it.name ==~ /.*\.java/ }

Then, you don't need Commons FileUtils

like image 145
tim_yates Avatar answered Sep 28 '22 09:09

tim_yates