views:

195

answers:

2

I have the following groovy code :


class FileWalker {
    private String dir

    public static void onEachFile(String dir,IAction ia) {
     new File(dir).eachFileRecurse {
      ia.perform(it)
     }
    }
}

walker = new FileWalker()
walker.onEachFile(args[0],new PrintAction())

I noticed that if I place a def in front of walker , the script works. Shouldn't this work the way it is now ?

A: 

In scripting mode (or via "groovyConsole"), you need a declaration of walker with "def" before using it. A Groovy script file is translated into a derivative class of class Script before it get compiled. So, every declaration needs to be done properly.

On the other hand, when you're running a script in "groovysh" (or using an instance of class GroovyShell), its mechanism automatically binds every referencing object without the need of declaration.

updated: My above answer would be wrong as I decompiled a .class of Groovy and found that it's using a binding object inside the script as well. Thus my first paragraph was indeed wrong.

chanwit
+1  A: 

You don't need a def in groovyConsole or in a groovy script. I consider it good programming practice to have it, but the language will work without it and add those types of variables to the scripts binding.

I'm not sure about the rest of your code (as it won't compile as you've posted it). But you either have a really old version of groovy or something else is wrong with your config or the rest of your code.

With the addition of a stub for the missing IAction interface and PrintAction class, I'm able to get it to run without modification:

interface IAction {
    def perform(obj)
}

class PrintAction implements IAction{
    def perform(obj) {
        println obj
    }
}
class FileWalker {
    private String dir

    public static void onEachFile(String dir,IAction ia) {
        new File(dir).eachFileRecurse {
            ia.perform(it)
        }
    }
}

walker = new FileWalker()
walker.onEachFile(args[0],new PrintAction())

I created a dummy directory with "foo/bar" and "foo/baz" files.

If I save it to "walkFiles.groovy" and call it from the command line with

groovy walkFiles.groovy foo

It prints:

foo/bar
foo/baz

This is with the latest version of groovy:

groovy -v
Groovy Version: 1.6-RC-3 JVM: 1.5.0_16
Ted Naleid