Skip to content

Invoking methods and functions

Andrey Kurosh edited this page Jul 20, 2017 · 5 revisions

To invoke a callable object (a method or a function), you should pass arguments to it, separated by spaces:

fun add:int (x:int y:int) -> x + y
    
let five = add 2 3
let ten = add 9 1

If a function does not accept any parameters, you should explicitly pass a unit literal to it:

fun log:DateTime ->
    let dt = DateTime::Now
    print "{0}: log is called" dt
    dt

let date = log ()     // log is called

Calling static methods

To call a static method, the type must be specified with a double semicolon delimiter:

let ab = string::Concat "a" "b"
let one = int::Parse "1"

Calling methods on objects

To call a method on an object, the dot operator should be used:

let a = 1
a.ToString ()

If the object is a complex expression (like an invocation), a multiline invocation with the |> operator can be used:

1.to 10
    |> ToArray ()

Passing multiline arguments

Sometimes you might want to pass a big expression as a parameter to a function, possibly even a multiline lambda function. There are two ways of doing that:

  1. Save the expression to a local variable (preferred):

    let check = (x:int) ->
        var y = x ** 2
        y <= 25
    
    let arr = new [1; 2; 3; 4; 5; 6; 7]
    Array::FindAll arr check
  2. Use the multiline argument passing with <| operator:

    Array::FindAll
        <| new [1; 2; 3; 4; 5; 6; 7]
        <| (x:int) ->
            let y = x ** 2
            y < 25

Extension methods

Extension methods are a syntactic sugar that lets static methods be called on an object. The compiler passes the object as the first argument to the method. This technique is heavily used in LINQ:

1.to 10
    |> Where x -> x % 2 == 0
    |> Select x -> x ** 2
    |> ToList ()

Moreover, any method that is declared in a LENS script can be called either statically or as an extension method:

fun add:int (x:int y:int) -> x + y

let three = add 1 2
let alsoThree = 1.add 2