How does a function return a value in EK9? There is no return keyword.

← Functions and Methods · Ref: Q1001

EK9 has no return keyword. Instead, you declare a return variable in the function signature with <-. The value of that variable when the function ends is what gets returned.

THE PATTERN:

  functionName() as pure
    -> inputParam as String           parameter coming IN
    <- rtn as String: "default"       return value going OUT

The <- rtn as String declares a variable called 'rtn'. You can set it with an initial value (: "default") or leave it unset (: String()). The compiler ensures all execution paths give rtn a value.

INSIDE THE FUNCTION:

Update rtn using := or : to change what gets returned:

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

If score >= 50, rtn becomes "pass". Otherwise rtn stays at its default "fail". Either way, the caller gets a String.

THE CALLER:

  result <- classify(75)     result is "pass"
  result2 <- classify(30)    result2 is "fail"

Example

defines module qa.functionsandmethods.returnsexplained

  defines function

    greetByName() as pure
      -> personName as String
      <- rtn as String: "Hello, " + personName

    classifyScore() as pure
      -> score as Integer
      <- rtn as String: "fail"

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

    findLarger() as pure
      ->
        first as Integer
        second as Integer
      <- rtn as Integer: first

      if second > first
        rtn: second

  defines program

    ReturnsExplainedDemo()
      stdout <- Stdout()

      // Simple return — initial value is the return
      message <- greetByName("Steve")
      stdout.println(message)

      // Conditional return — rtn updated inside if
      grade <- classifyScore(75)
      stdout.println(`Score 75: ${grade}`)

      grade2 <- classifyScore(30)
      stdout.println(`Score 30: ${grade2}`)

      // Two-path return
      bigger <- findLarger(10, 25)
      stdout.println(`Larger: ${bigger}`)

Common mistakes

E01072 — 'return' does not exist in EK9; assign the declared return variable with 'rtn: value' instead of 'return value', which triggers E01072. See ek9 -h E01072 for details.

Incorrect:

        return "pass"

Correct:

        rtn: "pass"
Other ways to ask this
  • Where does the return value come from if there is no return statement?
  • Explain the <- rtn pattern for returning values from functions
  • How does the compiler know what value to return from a function?

Coming from another language?

EK9 uses named return declarations instead of return statements. The declared return variable is automatically returned when the function completes.

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