Ari Manninen
Ari Manninen

Reputation: 528

Groovy calling generic method does not compile

I have Java 8 + Groovy 2.4.12 and code below compiles and runs.

import java.util.function.Consumer
import groovy.transform.CompileStatic

@CompileStatic
class Bar {

    public static <T> void foo(T a, Consumer<T> c) { c.accept(a) }

    static void main(args) {
        ['a','b'].each {
            int xyz
            xyz = 1
            foo('') {
                println '1'
                return
            }
        }
    }
}

But if you comment out the return, compiler says

Groovy:[Static type checking] - Cannot call <T> Bar#foo(T, java.util.function.Consumer <T>) with arguments [java.lang.String, groovy.lang.Closure 

Further on, if you comment out the xyz value assignment, then it's ok again. So, code below compiles and runs:

['a','b'].each {
    int xyz
//  xyz = 1
    foo('') {
        println '1'
    //  return
    }
}

This seems a special condition that occurs only when you have:

My question is; is this a compiler bug or is there a rational reason why it doesn't compile without return statement but compiles with it? Or why adding variable definition breaks it?

Upvotes: 0

Views: 977

Answers (1)

Jeff Scott Brown
Jeff Scott Brown

Reputation: 27245

My question is; is this a compiler bug or is there a rational reason why it doesn't compile without return statement but compiles with it?

The former.

Upvotes: 0

Related Questions