How do I assign a value based on a condition in EK9?

← Control Flow · Ref: Q984

EK9 provides three patterns for conditional value assignment:

PATTERN 1: IF/ELSE ASSIGNMENT

  label <- "standard"
  if score > threshold
    label := "premium"

PATTERN 2: SWITCH EXPRESSION

  category <- switch rating
    <- rtn as String?
    case > highMark
      rtn: "excellent"
    case > passMark
      rtn: "good"
    default
      rtn: "needs improvement"

PATTERN 3: COALESCING (?: and :=?)

  displayName <- userName ?: "Guest"
  fallback :=? computeDefault()

Choose if/else for simple binary conditions. Choose switch expression for multiple cases. Choose ?: or :=? when providing defaults for unset values. Not ?? - it only replaces an ABSENT value, so an unset one passes straight through (see Q1059).

Example

defines module qa.controlflow.conditionalvalue

  defines function

    classifyTemperature() as pure
      -> celsius as Float
      <- rtn as String?

      coldThreshold <- 10.0
      hotThreshold <- 30.0

      rtn: switch celsius
        <- category as String?
        case < coldThreshold
          category: "cold"
        case > hotThreshold
          category: "hot"
        default
          category: "mild"

  defines program

    ConditionalValueDemo()
      stdout <- Stdout()

      // Pattern 1: if/else assignment
      temperature <- classifyTemperature(15.0)
      descriptor <- "unknown"
      if temperature?
        descriptor := temperature
      stdout.println(`Descriptor: ${descriptor}`)

      // Pattern 2: switch expression
      weather <- classifyTemperature(22.0)
      stdout.println(`Weather: ${weather}`)

      // Pattern 3: coalescing for defaults
      nickname <- String()
      displayName <- nickname ?: "Anonymous"
      stdout.println(`Name: ${displayName}`)
Other ways to ask this
  • How do I choose between two values based on a condition in EK9?
  • What replaces conditional value assignment in EK9?
  • How do I write a one-line conditional in EK9?
  • How do I assign different values depending on a test?

Coming from another language?

Other languages use a conditional expression for this. EK9 uses if/else assignment, switch expressions, or the coalescing operator ?: (Elvis) depending on the scenario.

Keywords: if else, switch expression, value, conditional, choose, assign