"include" functions in groovy script

I am writing some scripts in groovy. And I need some kind of code reuse in my scripts. How can i do this?

  • I can put this code in a class. But it is hardly worth supporting the solution - part of the code is in the interpreted script, and the other in the compiled class
  • I can use 'evaluation', but I need to reuse a function that has a return value. I tried to "evaluate" function definitions and did not seem to work.

Can you recommend some approach to β€œinclude” function definitions in a script?

Thanks!

+2
source share
1 answer

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

Take the file SomeClass.groovy

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

and script SomeScript.groovy

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

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

edits

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

Call as:

 println(SomeClass.add(1,1)) 
+2
source

Source: https://habr.com/ru/post/950058/


All Articles