gw666 (1) [Avatar] Offline
#1
I'm using the latest version of Groovy (1.5.7). I was using Groovy to learn about formatting strings, and I was getting error messages were I shouldn't have. I searched the Internet for an answer, but I didn't find anything.

Here's some code from Sun's Java 1.5 doc pages; it works just as you would expect it in Java:

-----------------------------------------
import java.util.Calendar;
import java.util.GregorianCalendar;
import static java.util.Calendar.*;

public class Scratch {

public static void main(String[] args) {
Calendar c = new GregorianCalendar(1995, MAY, 23);
String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c);
System.out.println(s);
// -> prints "Duke's Birthday: 5 23, 1995"
}
}
-----------------------------------------

Here's the code that I put into the GroovyConsole window:

-----------------------------------------
import java.util.Calendar;
import java.util.GregorianCalendar;
import static java.util.Calendar.*;
Calendar c = new GregorianCalendar(1995, MAY, 23);
String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c);
System.out.println(s);

... and here's the output:

Exception thrown: groovy.lang.MissingPropertyException: No such property: tm for class: Script4

groovy.lang.MissingPropertyException: No such property: tm for class: Script4
at Script4.run(Script4:5)
-----------------------------------------

If you take out the import statements, you get a different error:

Exception thrown: groovy.lang.MissingPropertyException: No such property: MAY for class: Script5

groovy.lang.MissingPropertyException: No such property: MAY for class: Script5
at Script5.run(Script5:1)
-----------------------------------------

Any ideas why this is happening? Thanks.
Mittie (397) [Avatar] Offline
#2
Re: This doesn't work in Groovy--why?
Hi Gregg,

this forum is for Groovy-in-Action related questions only. For general Groovy questions, the Groovy mailing lists are a better choice since you will reach a wider audience and more readers will profit from answers.

That said, your case has a simple solution, so I post it here anyway...
Replace line 5 with

String s = String.format('Duke\'s Birthday: %1$tm %1$te,%1$tY', c);

You used the GString syntax with double quotes, where $placeholders are resolved but the resolution was not possible ($tm, $te, $tY not known). The solution uses single quotes to declare a literal String.

keep groovin'
Dierk