| Literals | Assigment | Operator | Instanceof | Delegates | Lambda |
Delegates are a powerfull mechanism to implement
function level dispatching, callbacks and signal/slot mechanism.
DelegateExpression
: 'delegate' TypeOrVarName '.' MethodName
| 'delegate' '(' Expression ')' '.' MethodName
| MethodName
;
The delegate converts a class or object method in a Delegate instance.
Delegate is a shortcut to acdk::lang::dmi::DmiDelegate.
There are three forms of delegate usage:
1.
'delegate' TypeOrVarName '.' MethodName
TypeOrVarName can be
- a variable
- a member variable (like
acdk.lang.System.out )
- a Class name
MethodName is the name of a method.
2.
'delegate' '(' Expression ')' '.' MethodName
The Expression has to be evaluated to an Object instance.
3.
'delegate' MethodName
This form of delegate is only valid if used inside
a - static or non static - method.
See Sample:
class AClass
{
String prefix;
AClass(String pref)
{
prefix = pref;
}
// callback function
static RString GetGerText(String name)
{
return "Hallo " + name;
}
// other callback function
static RString GetEngText(String name)
{
return "Hello " + name;
}
// non static method callback function
String getEngText(String name)
{
return "Hello " + prefix + " " + name;
}
// this method uses a delegate:
static void useDelegate(Delegate del)
{
out.println(del.call("ACDK"));
}
static void DelegateInsideClass()
{
// inside a class method with 'delegate' methods can be used directly
useDelegate(delegate GetEngText);
}
void delegateInsideClass()
{
// inside a class method with 'delegate' methods can be used directly
useDelegate(delegate getEngText);
}
}
AClass.useDelegate(delegate (new AClass("superb")).getEngText);
// use a static method (english)
AClass.useDelegate(delegate AClass.GetGerText);
// now use english text
AClass.useDelegate(delegate AClass.GetEngText);
AClass cls = new AClass("finest");
// Delegates works also with non-static methods
AClass.useDelegate(delegate cls.getEngText);
// using expression
AClass.useDelegate(delegate (new AClass("superb")).getEngText);
// see AClass.DelegateInsideClass
AClass.DelegateInsideClass();
// see AClass.delegateInsideClass
cls.delegateInsideClass();
// what the implementation of the delegate does:
AClass.useDelegate(new DmiDelegate(AClass.GetClass(), "GetGerText"));
|
Delegates works also with native ACDK C++ implemented methods:
class AClass
{
// callback function
static void println(String name)
{
out.println("AClass: " + name);
}
}
DelegateArray delegates = new DelegateArray(0);
// script implementation
delegates.append(delegate AClass.println);
// native ACDK C++ implemenation of println
delegates.append(delegate acdk.lang.System.out.println);
foreach (Delegate dlg in delegates)
{
dlg.call("A Text");
}
|
See also: Lambda.
See also: Calling Interface.
Samples
|