views:

43

answers:

1

I have the following code:

public class TestGr
{
  static String aaa = "wwww";

  public static void main(args)
  {
    println "["+getAAA()+"]";
    println "[" + getBBB() +"]";
  }

  static String getAAA()
  {
    return ""
    + "${aaa}"
  }

  static String getBBB()
  {
     return "" + "${aaa}" 
  }
}

The output of this code is:

[]
[wwww]

I do not understand why in the first call I get an empty string. Does anybody know why a line break change the output of a function?

+2  A: 

It's the way the groovy is being parsed. Since semicolons at the end of statements are optional, newlines sometimes make a difference.

getAAA() is being parsed as two statements, like this:

static String getAAA() {
    return "";
    +"${aaa}";
}

Even though the unary + operator doesn't make sense with a string arg, groovy can't catch it due to its dynamic nature. There might be a postive() meta method on string that would make it valid.

EDIT:

For a better idea of what's going on, start up groovyConsole and load your script. Select "Inspect AST" from the Script menu. You'll see something like this:

AST Browser Image

ataylor
No, even if you drop the optional `return` statement, there's no way I can think of to join the `aaa` string onto the previous statement without doing some complex AST manipulation. At least dropping the optional `return` makes this throw an error
tim_yates
@Ataylor: thanks for help. I have to say that -- if somebody is not aware of this groovy feature -- it can cause an extremely hard to find bug.
Skarab