XPAND foreach-loop ITERATOR available in xtend2?

1,721 views
Skip to first unread message

sv3n....@gmail.com

unread,
Jun 19, 2012, 8:45:20 AM6/19/12
to xtend...@googlegroups.com
hi,

i have a for-loop in one of my xtend2 template expressions and i would
like to use a counter/index/iterator with it.

in xpand i was able to do:

«FOREACH values AS value ITERATOR idx»
«value.method(idx.counter1, this)»
«ENDFOREACH-»

how can i do this in xtend2? do i have to use the while-loop (with
managing my own counter) instead or is there something similar to
xpands ITERATOR available in xtend2?

best
sven

Sebastian Zarnekow

unread,
Jun 19, 2012, 8:56:16 AM6/19/12
to xtend...@googlegroups.com
Hi Sven,

that's not yet supported.
You may want to follow this ticket: https://bugs.eclipse.org/bugs/show_bug.cgi?id=368324

In Xtend you can do something like

<<FOR i: 1..elements.size>>
<<elements.get(i - 1).method(i)>>
<<ENDFOR>>

Regards,
Sebastian
signature.asc

sv3n....@gmail.com

unread,
Jun 19, 2012, 9:04:11 AM6/19/12
to xtend...@googlegroups.com
feels slightly better than my current approach:

def template(Blah blah) {
var idx = 0
'''
«FOR value : myValues»
«value.method(idx, blah)»
«idx=idx+1»
«ENDFOR»

'''
}

i will follow the ticket. thanks!

digulla

unread,
Jun 20, 2012, 5:25:06 AM6/20/12
to xtend...@googlegroups.com
Am Dienstag, 19. Juni 2012 14:56:16 UTC+2 schrieb Sebastian:

<<FOR i: 1..elements.size>>
  <<elements.get(i - 1).method(i)>>
<<ENDFOR>>

Note that due to bugs/features in the iterator, this breaks when the collection can be empty.
 
Regards,

A. Digulla

Sven Efftinge

unread,
Aug 16, 2012, 11:02:30 AM8/16/12
to xtend...@googlegroups.com
Nice! :-)

On Aug 16, 2012, at 4:01 PM, Markus <markus...@googlemail.com> wrote:

I've realized it with plain xtend2 and it works like a charm for me:
 
@Data public class ListItem<T>
{
  T value
  int index
  boolean isFirst
  boolean isLast
}
 
def <T> indexed(Iterable<T> list)
{
  var List<ListItem<T>> result = newArrayList
  val lastIndex = list.size - 1
  var currentIndex = 0
 
  for (item : list)
  {
    result += new ListItem<T>(
      item,
      currentIndex,
      currentIndex == 0,
      currentIndex == lastIndex
    )
  }
   
  return result
}
 
Usage:
 
«FOREACH it : values.indexed»
  «value.method(index)»
«ENDFOREACH-»
 
Especially in combination with the "it" feature it is quite as easy to use as the old xpand solution - and it is extendible as well.

Reply all
Reply to author
Forward
0 new messages