Groovy method calling syntax

Viewed 80

I am quite new to groovy and getting following error when running the below method.

def hi() {
    println("Hello World!")
}

hi()

def runHi() {
    println("Running hi()")
    hi()
}

runHi()

It'll give:

===> true
Hello World!
===> null
===> true
Running hi()
ERROR groovy.lang.MissingMethodException:
No signature of method: groovysh_evaluate.hi() is applicable for argument types: () values: []

I don't understand why hi() can run by itself but not within another method.

I've also tried:

static def hi() {
    println("Hello World!")
}

hi()

static def runHi() {
    println("Running hi()")
    hi()
}

runHi()

And that gives exact same error as well.

No signature of method: static groovysh_evaluate.hi() is applicable for argument types: () values: []

What's the problem and how to fix it?

1 Answers

That should run fine as a script. If you're running it through the Groovy Shell, you need to turn on interpreter mode:

Shell variables are all untyped (i.e. no def or other type information). This will set a shell variable: foo = "bar" But, this will evaluate a local variable and will not be saved to the shell’s environment: def foo = "bar" This behavior can be changed by activating interpreter mode.

See http://www.groovy-lang.org/groovysh.html.

Related