Language reference · section 9

9. Functions

Feature: Functions

  Scenario: A function has an explicit return
    Given the code:
      """
      fn name(a, b):
        return a + b
      """
    Then the function returns a + b

  Scenario: A return type follows the parameters
    Given the code "fn f(n: int): int:"
    Then the return type is int

  Scenario: A concise arrow has one expression
    Given the code "double = (x) -> x * 2"
    Then double(4) is 8

  Scenario: A block arrow is the value of a binding
    Given the code "double = (x) ->:" with "return x * 2" in its body
    Then double(4) is 8

  Scenario: A default value applies when the caller passes nothing
    Given the code "fn greet(name, greeting = \"hello\"):"
    When the caller writes greet("Ada")
    Then greeting is "hello"

  Scenario: A mut parameter cannot have a default value
    Given the code "fn f(mut c = 1):"
    Then the compiler reports an error "a `mut` parameter cannot have a default value yet"

  Scenario: An arrow uses the this of the code around it
    Given an arrow inside a class method
    When the arrow reads this
    Then this is the receiver of the method

  Scenario: async makes a function return a promise
    Given the code "async fn f():" with "return 1" in its body
    When the caller awaits f()
    Then the result is 1