javastringtemplatestringtemplate-4

Weird NullPointerException in StringTemplate map operation


This is my StringTemplate template for generating import statements, which does map operation on the anonymous template {i | import <i>;<\n>} for every value in imports .

importdecl(imports) ::= "<if(imports)> <imports: {i | import <i>;<\n>}> <endif>"

This throws java.lang.NullPointerException at org.stringtemplate.v4.misc.ErrorManager.runTimeError(ErrorManager.java:133).

And the weird part is, when I change i to something else, this works perfectly and I'm sure that there is no difference in the input in both the cases. Like this doesn't throw error,

importdecl(imports) ::= "<if(imports)> <imports: {r | import <r>;<\n>}> <endif>"

Is i reserved or something in StringTemplate or am I missing something?


Solution

  • <i> is used to access the 1 based index in the array.

    For example,

    ST st = stGroup.getInstanceOf("importdecl");
    int[] data = {4, 5};
    st.add("imports", data);
    System.out.println(st.render());
    

    with a template of

    importdecl(imports) ::= <<
      <if(imports)><imports: {k | import <i><k>;<\n>}><endif>
    >>
    

    Prints:

    import 14;
    import 25;
    

    I'd suggest using a different variable name :)

    More info here and here