Write a function that returns a set or unset String depending on input.

← Functions and Methods · Ref: Q1167

String() creates an unset return; caller guards with ?:

  <- colour as String: String()
  if name == "sky"
    colour: "blue"

If the condition doesn't match, the return stays unset. Caller uses if-guard: if found <- findColour("sky"). See Q1146, Q1087.

Example

defines module qa.functionsandmethods.functionoptionalreturn

  defines function

    findColour() as pure
      -> name as String
      <- colour as String: String()
      if name == "sky"
        colour: "blue"
      else if name == "grass"
        colour: "green"

  defines program

    FunctionOptionalReturnDemo()
      stdout <- Stdout()

      //Found — guard executes block
      if skyColour <- findColour("sky")
        stdout.println(`Sky: ${skyColour}`)

      //Not found — guard skips block
      if oceanColour <- findColour("ocean")
        stdout.println(`Ocean: ${oceanColour}`)
      else
        stdout.println("Ocean colour not found")

Common mistakes

E08180 — EK9 doesn't use Optional for function returns. Return an unset value (String()) and let the caller guard with ?.

Incorrect:

      <- colour as Optional of String

Correct:

      <- colour as String: String()
Other ways to ask this
  • I need a function that sometimes returns a value and sometimes returns nothing
  • In Java I'd return Optional<String>. Write the EK9 function with optional return
  • Given a lookup function, return the found value or leave the return unset
  • Create a function whose return can be checked with ? by the caller

Coming from another language?

Java: Optional<String>. Kotlin: String?. Rust: Option<String>. EK9: return String() (unset) or a value — caller uses ? or guard.

Keywords: unset, lookup, optional, function, guard, return