5

假设您在 xTend 中有以下代码:

class StackOverflowGenerator {
    def generate()'''
    «var counter = 0»
    «FOR i : 0 ..<10»
    Line Numnber: «i»
    «counter = counter + 1»
    «ENDFOR»
'''

}

这将生成以下格式的输出:

    Line Numnber: 0
    1
    Line Numnber: 1
    2
    Line Numnber: 2
    3
    Line Numnber: 3
    ...

如何让 xTend 不仅使用计数器打印行,而仅打印行号行,以使输出如下所示:

Line Numnber: 0
Line Numnber: 1
Line Numnber: 2
Line Numnber: 3
...
4

3 回答 3

9

在 Xtend 中,一切都是一个表达式,因此«counter = counter + 1»计算赋值的结果,这就是为什么它将成为字符串的一部分。因此,如果您真的想在模板表达式的 for 循环中执行副作用(强烈建议不要这样做),请在块表达式中执行并返回空字符串或 null: «{ counter = counter + 1; "" }»。然而,这不是太优雅,所以你可能想以另一种方式解决你的问题,正如其他答案所暗示的那样。

于 2013-10-04T08:38:57.277 回答
3

In your example there is no use for counter. So it is hard to guess what your real usecase is. In most cases some calculation based on i is enought, eliminating counter completely. Orionll's answer is pointing in that direction.

If however counter is something which cannot be computed from i but is some accumulated state, then the simplest thing is to extract that state into a custom class and to modify this state using void methods. In this example the generated void setCounter(int) method is used.

class Example {
    def static void main(String[] args) {
        println(generate)
    }

    def static generate() '''
        «var state = new State(0)»
        «FOR i : 0 ..< 10»
            Line Numnber: «i»
            «state.setCounter(state.counter + 1)»
        «ENDFOR»
    '''

}

class State {
    @Property
    var int counter

    new(int counter){
        this.counter = counter
    }
}
于 2013-08-31T16:28:23.887 回答
1
«var counter = 0»
«FOR i : 0 ..<10»
Line Number: «counter = i»
«ENDFOR»
于 2013-08-24T09:38:51.080 回答