Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass param with .& operator to a static method

With groovy .& operator one can create references to static methods, as in

def static xyz( name='Joe' ) {
 println "Hello ${name}"
}

// NOTE: ConsoleScript number part varies
def ref = ConsoleScript52.&xyz

And can be easilly called without params, as

ref()  // prints "Hello "

But how can this method be called with params? ref('John') gives an error groovy.lang.MissingMethodException: No signature of method: ConsoleScript52.xyz() is applicable for argument types: (java.lang.String) values: [John]

Note that Groovy does not even use the default value of name param in above example when static method is called with ref.

like image 325
kaskelotti Avatar asked May 21 '26 16:05

kaskelotti


1 Answers

You are probably using a ConsoleScript instance where you did not define that method with parameters.

In the code below, in the 8th execution in my console (ConsoleScript8) y defined the method hello() without parameters (added the "script number" to make it explicit):

println this.getClass().getName()
println ''

def static hello() {
    println "(8) Hello"
}

def h8 = ConsoleScript8.&hello
h8()
h8('Joe')

And it yields the following in the next execution:

ConsoleScript9

(8) Hello
Exception thrown

groovy.lang.MissingMethodException: No signature of method: ConsoleScript9.hello() is applicable for argument types: (java.lang.String) values: [Joe]

And in the 10th execution (ConsoleScript10) I modified it adding the default parameter:

println this.getClass().getName()
println ''

def static hello(name='amigo') {
    println "(10) Hello ${name}"
}

def h10 = ConsoleScript10.&hello
h10()
h10('Joe')

println '--'

def h8 = ConsoleScript8.&hello
h8()
h8('Joe')

And it yields:

ConsoleScript12

(10) Hello amigo
(10) Hello Joe
--
(8) Hello
Exception thrown

groovy.lang.MissingMethodException: No signature of method: ConsoleScript8.hello() is applicable for argument types: (java.lang.String) values: [Joe]

It is easier if you use an explicit class:

class Greeter {
    def static hello(name='Joe') {
        "Hello ${name}"
    }
}

def hi = Greeter.&hello
assert hi() == 'Hello Joe'
assert hi('Tom') == 'Hello Tom'
like image 197
jalopaba Avatar answered May 24 '26 22:05

jalopaba