3

I want to count a value inside a template expression, in Xtend, without printing it out.

This is my code:

def generateTower(Tower in) {
    var counter = 0.0;
'''
One         Two             Three           Four
«FOR line : in.myTable»
«counter»   «line.val1»     «line.val2»     «line.val3»
«counter = counter + 1»
«ENDFOR»
'''
    }

So this will generate a table with four columns, whereas the first column is incremented starting at 0.0. The problem is, that «counter = counter + 1» is printed as well. But I want the expression above to just count up, without printing it out.

What could be the best solution to solve this problem?

John
  • 795
  • 3
  • 15
  • 38

3 Answers3

3

You could use this simple and readable solution:

«FOR line : in.myTable»
«counter++»   «line.val1»     «line.val2»     «line.val3»
«ENDFOR»

If you insist on the separate increment expression, use a block with null value. This works because the null value is converted to empty string in template expressions (of course you could use "" as well):

«FOR line : in.myTable»
«counter»   «line.val1»     «line.val2»     «line.val3»
«{counter = counter + 1; null}»
«ENDFOR»

Although the first solution is the better. If you require complex logic in a template expression I recommend implementing it by methods not by inline code...

And finally, here is a more OO solution for the problem:

class TowerGenerator {
    static val TAB = "\t"

    def generateTower(Tower in) {
        var counter = 0

        '''
            One«TAB»Two«TAB»Three«TAB»Four
            «FOR line : in.myTable»
                «generateLine(line, counter++)»
            «ENDFOR»
        '''
    }

    def private generateLine(Line line, int lineNumber) '''
        «lineNumber»«TAB»«line.val1»«TAB»«line.val2»«TAB»«line.val3»
    '''
}
snorbi
  • 2,590
  • 26
  • 36
1

Xtend is a full-fledged programming language. You can write Java-like expressions and templates. The problem there is that you're inside a triple quote (template), and everything you write there gets outputted. You can count inside the loop, but take into account that you're counting the elements in the in.myTable collection, and this can be obtained using in.myTable.length. So count could be calculated beforehand as in.myTable.length.

Diego Sevilla
  • 28,636
  • 4
  • 59
  • 87
0

«{counter = counter + 1; null}» definitely worked. But as a recommendation, since it is java, writing it as «{counter++; null}» should do the trick as well. It helps because, you may need to modify your code and you can also put it in front as in: ++counter - by putting the operator first, the compiler takes a number, adds one to it before reading the value.

ask4jubad
  • 23
  • 6