Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In groovy is it legal to reference private member variables from within a closure?

Tags:

groovy

Sample code which can easily be run in the GroovyConsole under groovy 2.4.4:

import groovy.transform.CompileStatic

class Echo {
    public void text(String txt) {
        println txt
    }
}

class Test {
    private Echo echo = new Echo()
    @CompileStatic
    public void doStuff() {
        Closure c = {
            echo.text('hi')
        }
        c()        
    }
}

new Test().doStuff()

It fails with java.lang.ClassCastException: Test$_doStuff_closure1 cannot be cast to Test.

Interestingly, if I remove the @CompileStatic annotation or make the member variable non-private it works as expected.

Edit: filed JIRA issue GROOVY-7558

like image 638
jckdnk111 Avatar asked Aug 25 '15 19:08

jckdnk111


1 Answers

I think you've uncovered a bug. If it were expected that @CompileStatic would disallow access to the private variable, than this should fail too

import groovy.transform.CompileStatic

class Echo {
    public void text(String txt) {
        println txt
    }
}

@CompileStatic
class Test {
    private Echo echo = new Echo()

    public void doStuff() {
        Closure c = {
            echo.text('hi')
        }
        c()
    }
}

new Test().doStuff()

But it doesn't. There are some Jiras that might be the same issue (GROOVY-6278, GROOVY-7165, GROOVY-6468), but I'm not sure if the root cause is the same. I'd say go ahead an open a new Jira for this.

like image 64
Keegan Avatar answered Oct 18 '22 17:10

Keegan