Wiki
Version 2 (modified by todd.a, 14 years ago)

--

Delegates

(also known as typesafe (function) method pointers).

A delegate is a type that safely encapsulates a method of a specific signature (method return type and parameters).

A reference to any method that matches the delegate's signature can be assigned to the delegate.

Once a delegate is assigned a method, it behaves exactly like that method and can be used like any other method, with parameters and a return value.

The type of a delegate is defined by the name of the delegate.

In cobra, delegates are declared as "method signatures" and define a type: e.g

sig FunctionWithOneIntArgAndReturnsBool(i as int32) as bool

Here the delegate type name is "FunctionWithOneIntArgAndReturnsBool"

The following is the usual set of steps in declaring a delegate type, a conforming method and instantiating and invoking the delegate.

# The following declares a delegate (type) named Del that can 
#encapsulate a method that takes a string  as an argument and returns void:
sig Del(message as String)
...
# a method that conforms to the delegate Type
def delegateMethod(msg as String)
    Console.writeline(msg)
...
    
# Instantiate the delegate.
handler as Del = .ref delegateMethod

# invoke the delegate.
handler("Hello World");

Grammar

# delegate definition
sig TYPENAME(ARGS) as TYPE

# delegate instantiation
name as SIGTYPENAME = ref METHODNAME

# delegate invocation
name        # no arg delegate
name(ARGS)

Examples

class SigEG
    sig IntTest(i as int) as bool

    def tstInt( i as int) as bool is shared
        return i > 47

    def main is shared
        tester as IntTest = ref .tstInt
        assert tester(99) 
        assert not tester(3) 
# as above using an anon function
    tester as IntTest = do(i as int)
    return i > 47

    assert tester(99) 
    assert not tester(3) 

# using a lambda expression     
    tester = do(i as int) = i > 100
    assert not tester(99) 
    assert tester(103) 

Notes

Type inference on delegate variables and method references is not all it could be so currently delegate variable definitions need a type definition.

name as SIGTYPENAME = ref METHOD
# rather than just
name = ref METHOD