Gangmax Blog

Include a groovy script in another

From here.

With the following three groovy files:

f1.groovy
1
2
3
getName = { ->
return "${getFirstName()} ${getLastName()}"
}
f2.groovy
1
2
3
4
5
6
7
getFirstName = { ->
return "Max"
}

getLastName = { ->
return "Huang"
}
main.groovy
1
2
3
evaluate(new File("./f1.groovy"))
evaluate(new File("./f2.groovy"))
println("Hello, ${getName()}!")

Run the following command:

1
2
$ groovy main.groovy 
Hello, Max Huang!

Note that defining function directly cannot work, such as “def getName() {return “Max”;}”. Groovy reports the following error:

1
2
3
4
5
6
$ groovy main.groovy 
Caught: groovy.lang.MissingMethodException: No signature of method: main.getName() is applicable for argument types: () values: []
Possible solutions: getAt(java.lang.String), getClass()
groovy.lang.MissingMethodException: No signature of method: main.getName() is applicable for argument types: () values: []
Possible solutions: getAt(java.lang.String), getClass()
at main.run(main.groovy:2)

Comments