I had a similar usecase and realized forEach won't help the way I used it.
So I thought closures are a solution:
@Test
public void test() {
Closure modify = closure();{
of(Point.class).setLocation(var(Point.class).x+10, 10);
}
List<Point> points = new ArrayList<>();
points.add(new Point(10, 0));
points.add(new Point(10, 10));
modify.each(points);
for (Point point : points) {
assertEquals(20, point.getX(), 0.0);
}
}
But the asserts fails since the object in the collection is not been modified. Maybe I'm doing something wrong there.
In the end I used closures from the apache commons collection.
UPDATE
I was able to solve the puzzle with a closure. Looks like you can't use the free variable direct. Here is the working code:
@Test
public void test() {
Closure modify = closure();{
of(this).visit(var(Point.class));
}
List<Point> points = new ArrayList<Point>();
points.add(new Point(10, 0));
points.add(new Point(10, 10));
modify.each(points);
for (Point point : points) {
assertEquals(20, point.getX(), 0.0);
}
}
void visit(Point p) {
p.setLocation(p.x + 10, p.y);
}
Note: instead of this
you can also write a class which contains the visit
method and use it in the definition of the closure
.