Details
-
Bug
-
Status: Closed
-
Major
-
Resolution: Duplicate
-
None
-
None
-
None
Description
I have the following Groovy program
class Foo { void foo() {} } class Main { static void bar() { def x = new Foo(); if (false) { x = null; } x.foo(); // works } static void baz() { def x = new Foo(); def clos = { -> { x = null; }} x.foo(); // fails } }
Actual behaviour
The assignment that takes inside closure changes the type of variable `x`, even though closure is never being called.
The compilerthen rejects the program by raising the following error message.
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: test.groovy: 22: [Static type checking] - A closure shared variable [x] has been assigned with various types and the method [foo()] does not exist in the lowest upper bound of those types: [java.lang.Object]. In general, this is a bad practice (variable reuse) because the compiler cannot determine safely what is the type of the variable at the moment of the call in a multithreaded context. @ line 22, column 5. x.foo(); ^ 1 error
Expected behaviour
Compile successfully
Tested against master (https://github.com/apache/groovy/commit/5601ea14304b67e71586b0196e38f90fa1a46f5b).