tags:

views:

41

answers:

1

IntelliJ highlights the 'foo' variable in gray, and says "assignment is not used". What I want to know is - it is right or not...

If this were java and not groovy, I know it wouldn't be right.

public class Foo
{
  public Foo()
  {
    Foo foo = null; // this 'foo' instance is gray ("assignment not used")
    try
    {
      foo = new Foo()
      // ...
    }
    finally
    {
      if (foo != null)
        foo.release();
    }

  }

  public void release(){}
}
+2  A: 

Groovy (and Java) variables are always initialized to null: Java Language Specification: Initial Values of Variables.

Edit: The above doesn't apply to local variables. In Java they always have to be assigned explicitly. I can't find any reference to this in the groovy spec. However, examining some local variable declarations with the groovyConsole AST browser confirms that groovy implicitly assigns null to local variables.

ataylor
This does not apply to stack/local variables. Trying reading a local variable without initializing it first, and you're in for a compilation error.
ripper234
Oops, sorry, you are correct. Java requires [Definite Assignment](http://java.sun.com/docs/books/jls/third_edition/html/defAssign.html) to be proved by the compiler. I can't find any reference to this in the groovy spec. However, examining some local variable declarations with the groovyConsole AST browser confirms that groovy implicitly assigns null to local variables.
ataylor
Cool, so this is in fact not a bug in IntelliJ.
ripper234
If you edit your answer to include this, I'll accept it.
ripper234