While loop in Xtend

242 Views Asked by At

I have written a code in java and now I have to convert it to Xtend templates. However I have the following written with a while loop.

index = refin.size()-1
                    while (index > 0){
                          System.out.println(refin.get(index) + "::=" + refin.get(index-1))
                          index-=2
                        }

Now I see that Xtend templates do not support WHILE, and also I cannot write the following:

«FOR index : refin.size()-1 ; index >= 0 ; index -=2»

Any ideas on how I could use that while loop (or something similar) to do the same thing that I am doing there, in Xtend templates?

Many thanks!

2

There are 2 best solutions below

0
Christoph S. On

For me it works fine

val String[] refin = #["1", "a", "2", "b", "3", "c"]
var index = refin.size - 1
while(index > 0) {
    println(refin.get(index) + "::=" + refin.get(index -1))
    index -= 2
}

// c::=3
// b::=2
// a::=1
0
kapex On

You are correct that Xtend supports neither for loops nor while loops within template expressions. Only for-each style loops are supported in templates. You could of course move the whole template string into a regular for loop or while loop but you may loose some benefits of template strings if you do that.

Your best option is to rewrite the for loop into a foreach-loop over an iterable range.

For the usual cases where the step size is 1 or -1, you can use range operators. Either inclusive like 0 ..< list.size to iterate forward or exclusive refin.size >.. 0 to iterate backwards, e.g.:

val String result = '''
    «FOR i : list.size >.. 0»
        «i»
    «ENDFOR»
'''

In your case where your step size is -2, you can't use range operators but you can use an org.eclipse.xtext.xbase.lib.IntegerRange instead, which allows you to define the step size:

val String[] refin = #["1", "a", "2", "b", "3", "c"]
val String result = '''
    «FOR i : new IntegerRange(refin.size - 1, 0, -2)»
        «refin.get(i)»::=«refin.get(i - 1)»
    «ENDFOR»
'''