Skarab
Skarab

Reputation: 7141

Why a concatenation of gstrings returned from a function is an empty string - Groovy 1.7.4

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?

Upvotes: 1

Views: 230

Answers (1)

ataylor
ataylor

Reputation: 66069

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

Upvotes: 3

Related Questions