tags:

views:

26

answers:

1

The following groovy script doesn't compile

import java.util.concurrent.Callable

println "b";
Callable<String> callable = new Callable<String>()
      {
        String call() {
          println("C");
          return null;
        }
      };

This is the error:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: C:\tmp\a.groovy: 6: Unknown type: METHOD_DEF at line: 6 column: 9. File: C:\tmp\a.groovy @ line 6, c olumn 9. String call() { ^

1 error

What is the cause and how to resolve?

+1  A: 

Try reformatting it like this:

import java.util.concurrent.Callable

println "b";
Callable<String> callable = new Callable<String>() \
    { 
        String call() {
            println("C");
            return null;
        }
    };

Because semicolons are optional, groovy is sensitive to newlines and occasionally parses a statement in a way that is unexpected. In this case, it considers Callable<String> callable = new Callable<String>() to be an entire statement. Java is smart enough to see that it's an anonymous inner class since the statement isn't terminated at the end of the line, but the first line is syntatically correct groovy and stops parsing.

The solution is to escape the newline with a backslash, to force groovy to continue parsing the statement. Alternatively, you could put the opening brace at the end of the line (i.e. standard java coding style).

ataylor
Thanks! I was a bit suspicious of how "semicolons are optional in groovy", and now I see I was right to mistrust this.
ripper234
No, there's no need to mistrust it...you just happened to hit one of the very few cases that would break it
tim_yates