Skip to content
impworks edited this page Oct 11, 2014 · 6 revisions

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

If the method is not overloaded (meaning the type has only one method with the same name), argument types may be omitted:

fun SomeCrazyMethodName:string (x:int y:int z:int) ->
    fmt "result = {0}" (x + y + z)

let fx = SomeCrazyMethodName
fx 1 2 3  // "result = 6"

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.

Read more

Clone this wiki locally