1

How can I call a callback function in xtend?

I am looking for something similar to the one in C. Example:

    struct callbacks
    {
      char name[10];
      boolean (*pfState)();
    };

    static const struct callbacks call[] = {
      {"YOURS", &isOwner},
      {"OURS", &our_owner}
    };

So, I will just call it like this: call[0].pfState().

I have created a similar ArrayList in xtend.

    val you = new youModule()
    val our = new ourModule()
    val callbacks = newArrayList('YOURS' -> you.isOwner, 'OURS' -> our.isOwnder);

Am I doing this correctly? How can I execute the function call in the pair?

Viliam Simko
  • 1,711
  • 17
  • 31
chris yo
  • 1,187
  • 4
  • 13
  • 30

2 Answers2

0

Currently you create a list of Pairs which map strings to the result of the method invocation, e.g. assuming #isOwner returns a boolean, your list callbacks is currently a List<Pair<String, Boolean>>.

Instead, you have to wrap the invocation of #isOwner in a lambda expression:

val callbacks = newArrayList(
  'YOURS' -> [| you.isOwner ],
  'OURS' -> [| our.isOwnder ]
);

Now, callbacks has the type List<Pair<String, ()=>boolean>>, or in other words: List<Pair<String, Functions.Function0<Boolean>>>.

Sebastian Zarnekow
  • 6,609
  • 20
  • 23
  • I am getting an error with your implementation. Incompatible implicit return type. Expected java.util.ArrayList> or java.util.List[] but was java.util.ArrayList>> What's the | and [] for? – chris yo Jul 15 '13 at 05:19
0

If you have a "callback" stored in a variable, you need to invoke the function by calling apply on it.

Here is a simple example showing a hash map that contains two callbacks stored under 'YOURS' and 'OURS' key. When called, each callback function prints a different message and returns a boolean value.

    val callbacks = newHashMap(
      'YOURS' -> [| println("calling the first callback");  true  ],
      'OURS'  -> [| println("calling the second callback"); false ]
    )

    val result = callbacks.get("YOURS").apply

// result is: true
// console output is: calling the first callback
Viliam Simko
  • 1,711
  • 17
  • 31