22 Collection for elements
A collection literal can generate elements from another iterable.
norm
main() {
List<Integer> source = [1, 2, 3]
List<Integer> doubled = [
for (number : source) number * 2
]
for number : doubled {
printLine(number)
}
printLine(doubled.size())
}Expected output:
text
2
4
6
3The parenthesized for head belongs inside []: it contributes number * 2 once per source element. This builds a new list, unlike the statement loop in the iteration lesson.
Try it: Filter the generated list in the next lesson, then compare the outputs.
Precise rules: Reference.