Apply blocks let you execute operations in the context of an expression's result, using the implicit variable it. Similar to Kotlin's .apply{}. |
|
An apply block follows any expression with { }. Inside, it refers to the expression's value. |
class Person(str name, int age) {
func setName(str n) void { name = n; };
func setAge(int a) void { age = a; };
};
Person p = new Person("", 0) {
it.setName("John");
it.setAge(25);
};
|
Apply blocks work with arrays and dictionaries for initialization. |
array[int] arr = new array[int](5) {
it[0] = 1;
it[1] = 2;
it[2] = 3;
it[3] = 4;
it[4] = 5;
};
|
Apply blocks can be nested. |
class Point(int x, int y) {
func setX(int val) void { x = val; };
func setY(int val) void { y = val; };
};
class Line(Point start, Point end) {};
Line line = new Line(
new Point(0, 0), new Point(0, 0)
) {
it.start {
it.setX(10);
it.setY(20);
};
it.end {
it.setX(100);
it.setY(200);
};
};
|
They also work with primitives. |
int x = 5 {
it = it * 2;
};
# x = 10
|