Wilda
Wilda

Reputation: 533

Groovy compiler and non existing call method

Why the following code doesn't raise a compile error ?

  class TestCompile {
    void foo() {
        println 'hello'
    }

    void foo2() {
        foo3()
    }

    static main(args) {
        new TestCompile().foo2()
    }
}

When I compile:

groovyc TestCompile.groovy

No error occurs.

But when I run the code :

java -cp groovy-all-2.4.6.jar:. TestCompile

The expected error occurs :

Exception in thread "main" groovy.lang.MissingMethodException: No signature of method: TestCompile.foo3() is applicable for argument types: () values: []
Possible solutions: foo(), foo2(), find(), find(groovy.lang.Closure), wait(), any()
        at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:58)
        at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:81)
        at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:52)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:154)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:158)
        at TestCompile.foo2(TestCompile.groovy:7)
        at TestCompile$foo2.call(Unknown Source)
        at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:117)
        at TestCompile.main(TestCompile.groovy:11)

How can I the compiler raise a compilation error without to execute the class to have the error ?

Upvotes: 0

Views: 373

Answers (1)

Wilda
Wilda

Reputation: 533

as tim_yates says in the comment this is the default groovy beahviour, to force the compile detection I must annotate my class with @CompileStatic annotation:

import groovy.transform.CompileStatic

@CompileStatic
class TestCompile {
    void foo() {
        println 'hello'
    }

    void foo2() {
        foo3()
    }

    static main(args) {
        new TestCompile().foo2()
    }
}

This code raise a compile error:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
TestCompile.groovy: 10: [Static type checking] - Cannot find matching method TestCompile#foo3(). Please check if the declared type is correct and if the method exists.
 @ line 10, column 9.
           foo3()
           ^

1 error

. Thanks Tim !

Upvotes: 1

Related Questions