Show me different function signatures in EK9 — no params, one param, multiple params, with return.

← Functions and Methods · Ref: Q998

EK9 functions use -> for parameters IN and <- for the return value OUT.

NO PARAMS, NO RETURN:

  greet()
    stdout <- Stdout()
    stdout.println("Hello")

NO PARAMS, WITH RETURN:

  getVersion() as pure
    <- rtn as String: "1.0.0"

ONE PARAM, WITH RETURN:

  double() as pure
    -> number as Integer
    <- rtn as Integer: number * 2

MULTIPLE PARAMS, WITH RETURN:

  add() as pure
    ->
      left as Integer
      right as Integer
    <- rtn as Integer: left + right

Multiple parameters go on separate lines under ->. Single parameters can be on the same line as ->.

The <- declares the return variable. The caller receives whatever that variable contains when the function completes. There is no return keyword.

Example

defines module qa.functionsandmethods.variedsignatures

  defines function

    //No params, no return
    sayHello()
      stdout <- Stdout()
      stdout.println("Hello from EK9")

    //No params, with return
    getVersion() as pure
      <- rtn as String: "1.0.0"

    //One param, with return
    doubleValue() as pure
      -> number as Integer
      <- rtn as Integer: number * 2

    //Multiple params, with return
    addValues() as pure
      ->
        left as Integer
        right as Integer
      <- rtn as Integer: left + right

    //Param and conditional return
    absoluteValue() as pure
      -> number as Integer
      <- rtn as Integer: number

      if number < 0
        rtn: 0 - number

  defines program

    VariedSignaturesDemo()
      stdout <- Stdout()

      sayHello()
      stdout.println(`Version: ${getVersion()}`)
      stdout.println(`Double 21: ${doubleValue(21)}`)
      stdout.println(`Add 15+27: ${addValues(15, 27)}`)
      stdout.println(`Abs -42: ${absoluteValue(-42)}`)

Common mistakes

E01072 — 'return' does not exist in EK9. Use '<- rtn as Type: expression' to declare the return value in the function signature.

Incorrect:

      return left + right

Correct:

    <- rtn as Integer: left + right
Other ways to ask this
  • What are the different ways to declare functions in EK9?
  • How do -> and <- work in EK9 function signatures?
  • Show me EK9 functions with various parameter and return combinations

Coming from another language?

EK9 uses -> for input parameters and <- for return declarations. Multiple parameters go on separate lines under ->.

Keywords: parameter, signature, pure, function, arrow, return