How do I write a function that returns a value in EK9?

← Functions and Methods · Ref: Q997

Declare the return variable with <- in the function signature. The compiler ensures all paths initialise it. There is no return keyword.

SINGLE RETURN:

  calculateArea() as pure
    -> radius as Float
    <- rtn as Float: radius * radius * 3.14159

The <- rtn as Float declares a variable called 'rtn' that holds the return value. The caller receives whatever rtn contains when the function completes.

CONDITIONAL RETURN:

  classify() as pure
    -> score as Integer
    <- rtn as String: String()
    passingScore <- 50
    if score >= passingScore
      rtn: "pass"
    else
      rtn: "fail"

The compiler verifies that rtn is assigned on ALL paths. If any path leaves rtn unset, you get a compile error.

UNSET RETURN:

Returning an unset value is valid — the caller checks with ? or a guard:

  findUser() as pure
    -> userId as Integer
    <- rtn as String: String()
    //rtn stays unset if no match found

Example

defines module qa.functionsandmethods.returnpattern

  defines function

    calculateArea() as pure
      -> radius as Float
      <- rtn as Float: radius * radius * 3.14159

    celsiusToFahrenheit() as pure
      -> celsius as Float
      <- rtn as Float: (celsius * 9.0 / 5.0) + 32.0

    classify() as pure
      -> score as Integer
      <- rtn as String: String()

      passingScore <- 50
      if score >= passingScore
        rtn: "pass"
      else
        rtn: "fail"

  defines program

    ReturnPatternDemo()
      stdout <- Stdout()

      area <- calculateArea(5.0)
      stdout.println(`Area: ${area}`)

      fahrenheit <- celsiusToFahrenheit(100.0)
      stdout.println(`100C = ${fahrenheit}F`)

      grade <- classify(75)
      stdout.println(`Grade: ${grade}`)

Common mistakes

E01072 — 'return' does not exist in EK9. Declare the return variable with <- in the signature: '<- rtn as Type: expression'. The compiler ensures all paths initialise it.

Incorrect:

      return radius * radius * 3.14159

Correct:

    <- rtn as Float: radius * radius * 3.14159
Other ways to ask this
  • What is the syntax for function return values in EK9?
  • How do I declare what a function returns in EK9?
  • Show me the <- rtn pattern for EK9 functions

Coming from another language?

EK9 uses named return declarations instead of a return keyword. Like Go's named returns but mandatory — the compiler enforces all paths initialise the return variable.

Keywords: function, no return keyword, rtn, return, declaration