2

I'm writing a number of scripts in groovy. And I need some kind of code reuse in my scripts. How can I do it?

  1. I can put this code in a class. But it is hardly to support solution - part of code is in the interpreted script and the other is in compiled class
  2. I can use 'evaluate', but I need reuse of a function, which has return value. I tried "evaluate" of functions definitions and it seems to be not working.

Can you recommend some approach of "include" of functions definitions in a script?

Thank you!

Pavel Bernshtam
  • 4,232
  • 8
  • 38
  • 62

1 Answers1

2

There is no need to compile the groovy script, you can include a script defined as a class just fine.

Take a file SomeClass.groovy

class SomeClass {
    def add(a,b){
        return a+b
    }
}

and a script SomeScript.groovy

println(new SomeClass().add(1,1))

This will work as long as SomeClass.groovy is on the CLASSPATH.

EDITS

class SomeClass {
    def static add(a,b){
        return a+b
    }
}

Call as:

println(SomeClass.add(1,1))
Mark
  • 106,305
  • 20
  • 172
  • 230