Search code examples
groovygroovyshell

Reference things from imported class in groovysh


Say I have a SomeThings.groovy file:

def someVar = 'abc'
def someFunc(a) {
  a + 1
}

I start groovysh with the above file on the classpath and do:

groovy:000> import SomeThings
===> SomeThings
groovy:000>

All good. However:

groovy:000> someVar
Unknown property: someVar
groovy:000> someFunc(1)
ERROR groovy.lang.MissingMethodException:
No signature of method: groovysh_evaluate.someFunc() is applicable for argument types: (java.lang.Integer) values: [1]
groovy:000>

How do I reference someVar and someFunc from groovysh?


Solution

  • Modify SomeThings.groovy as below:

    //SomeThings.groovy
    someVar = 'abc' // remove def to make variable available to shell
    def someFunc(a) {
      a + 1
    }
    

    Then the file has to be loaded to shell as below (load SomeThings.groovy can also be used instead). :h or :help will show its usage.

    groovy:000> . SomeThings.groovy 
    ===> abc
    ===> true
    groovy:000> someVar
    ===> abc
    groovy:000> someFunc(1)
    ===> 2
    groovy:000>