User Tools

Site Tools


01_user_documentation:07_rgg_xl:02_xl:08_object:04_generator:01_generator_methods

Generator Methods

As generator expressions are handled by internal iterators, the declaration of generator methods, i. e., methods which return multiple values in succession, is easy. Such a method has to receive an additional argument for the consumer to which it can pass its return values one after another.

Basic declaration

Generator methods take as first argument a consumer. That consumer can consume any of the primitive type, or Object<T>. The consumer classes are called: XXXConsumer,ObjectConsumer<? extends T>, where XXX is the primitive type (e.g. IntConsumer).

// declaration of a generator method
void produce(IntConsumer consumer, int n) {
	for (int i = 0; i <= n; i++)
	{
	consumer.consume(i);
	}
}
 
// use of the method
public void run ()
{
	final int[] result = {0}; // use an array to simulate a "pointer" which can be given to the consumer
	produce(new IntConsumer(){ 
		public void consume(int i){
			result[0] += i;
		}
	}, 10);
	println(result[0]); // 55
}

Implicit consumer argument

If the first consumer argument is omitted in an invocation, the invocation is treated as a generator expression which yields all values to the implicit first argument. Thus, the generator method declared above can be used with:

public void run ()
{
	sum( produce(10) ); // 55
}

Simplified declaration

To have a more convenient syntax for the implementation of generator methods, we introduce a syntax for a method declaration using an asterisk after the return type and the new keyword yield. The following method is equivalent to the first declaration:

int* produce(int n) {
	for (int i = 0; i <= n; i++) {
		yield i;
	}
}
01_user_documentation/07_rgg_xl/02_xl/08_object/04_generator/01_generator_methods.txt · Last modified: 2025/08/20 10:32 by gaetan