-
Notifications
You must be signed in to change notification settings - Fork 11
Creating delegates
If no arguments have been passed to a method or a function, it is converted to a delegate instead of being callled. A delegate is a callable object that represents some method or function, but can be passed to another method or function as a parameter or saved to a local variable, array or anywhere else. It can be called at some time later.
Here's an example of creating a delegate: we're defining a nice short alias for a commonly called method.
let isEmpty = string::IsNullOrEmpty // shorthand
isEmpty "" // true
isEmpty "hello" // false
If the method or function is overloaded, it's possible to specify argument types to get the exact desired overload:
var abs = Math::Abs<int>
abs (-10)
abs 1.3 // compile error: abs accepts `int` only
You can also use a placeholder (_) instead of some arguments if the existing arguments match only one function:
fun test (x:int) -> print "a"
fun test (x:int y:int) -> print "b"
fun test (x:string y:int) -> print "c"
fun test (x:string y:int z:string) -> print "d"
let a = test<_> // single argument
let b = test<int, _> // 2 arguments, first is int
let d = test<_, _, _> // 3 arguments
let x = test<_, int> // compile error: "b" and "c" both match
By default, if a method returns any value it's being represented by a Func<> delegate, and an Action<> otherwise. You can cast the delegate to another using the type casting operator.