Groovy - check if a parameter is a function

In JavaScript, I check if a function parameter is a function:

function foo ( p ) {
    if ( typeof p === 'function' ) {
        p();
    }
    // ....
}

How can I do the same in Groovy?

+4
source share
2 answers

Groovy makes closures a first-class citizen. Each closure extends the abstract class groovy.lang.Closure<V>, and in the case of an undefined argument type, you can use instanceofit to check whether a parameter has been passed to the method is a closure. Something like that:

def closure = {
    println "Hello!"
}

def foo(p) {
    if (p instanceof Closure) {
        p()
    }
}

foo(closure)

Running this script generates the output:

Hello!

Using a specific type of parameter

Groovy ( ) . , p , , . :

def closure = {
    println "Hello!"
}

def foo2(Closure cl) {
    cl()
}

foo2(closure)
foo2("I'm not a closure")

, ( "Hello!" ), :

Hello!
Caught: groovy.lang.MissingMethodException: No signature of method: test.foo2() is applicable for argument types: (java.lang.String) values: [I'm not a closure]
Possible solutions: foo2(groovy.lang.Closure), foo(java.lang.Object), find(), find(groovy.lang.Closure), wait(), run()
groovy.lang.MissingMethodException: No signature of method: test.foo2() is applicable for argument types: (java.lang.String) values: [I'm not a closure]
Possible solutions: foo2(groovy.lang.Closure), foo(java.lang.Object), find(), find(groovy.lang.Closure), wait(), run()
    at test.run(test.groovy:18)

, , , , , .

+5

Groovy , p instanceof a Closure

def foo(p) {
    if (p instanceof Closure) {
        p()
    } else {
        println "p is $p and not a Closure"
    }
}

foo { -> println "I'm a closure" }
foo('tim')

:

I'm a closure
p is tim and not a Closure
+4

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


All Articles