xtend pass functions as parameters to other functions

In xtend everything is an expression. Thus you can pass a method to another method as a parameter in the following way:

We need the players:
(1) The calledFunction, which is passed as an argument,
(2) the callingFunction, which hands over the calledFunction,
(3) and the genericFunction, which receives the calledFunction.

The (3) genericFunction is always implemented like this:


def Type genericFunction((Type)=>Type calledFunction){
Type parameter = new Type()
val result = calledFunction.apply(parameter)
}

To implement (1) and (2) we have the alternatives (A) and (B):

A: (1) and (2) can be implemented as methods:

(1) calledFunction:
def Type calledFunction(Type parameter){
parameter.foobar
}

(2) callingFunction:
def Type callingFunction(){
genericFunction([Type parameter | parameter.calledFunction])
}
or , even better, in the case of only one parameter:
(2) callingFunction:
def Type callingFunction(){
genericFunction([calledFunction])
}


B: (1) can be implemented as a variable

(1) calledFunction:
(Type)=>Type calledFunction = [parameter | parameter.foobar]

(2) callingFunction:
def Type callingFunction(){
genericFunction(calledFunction)
}

I prefer A, as (1) and (3) are used normally and in (2) it is visible, that a function is given as a parameter.

Leave a Reply

Your email address will not be published. Required fields are marked *