I keep getting errors mixing up <- and := in EK9. What is the rule?

← Getting Started · Ref: Q881

Simple rule: '<-' is for the FIRST TIME. ':=' is for EVERY TIME AFTER.

  score <- 100      // first time: score is born here
  score := 200      // after: score already exists, update it
  score <- 300      // WRONG: creates a NEW variable, shadows the old one

If you use '<-' on a variable that already exists in an outer scope, you create a NEW local variable with the same name. The outer variable is unchanged. This is almost always a bug.

The compiler may warn you with E11031 if the variable name is too generic, or E08090 if the shadowed variable is never used after the shadowing declaration.

For function returns, '<-' declares the return variable:

  calculateTotal() as pure
    -> items as List of Integer
    <- total as Integer: 0    // '<-' declares return
    for item in items
      total += item            // ':=' implicit via +=

See Q22 for declaration rules. See Q879 for all three assignment operators.

Example

defines module qa.getting.started.declare.vs.assign

  defines function

    sumList()
      -> numbers as List of Integer
      <- total as Integer: 0

      for item in numbers
        total += item

  defines program

    DeclareVsAssign()
      stdout <- Stdout()

      //Correct: declare then assign
      message <- "hello"
      message := "updated"
      stdout.println(message)

      //Demonstrate with a list
      scores <- List() of Integer
      scores += 10
      scores += 20
      scores += 30

      result <- sumList(scores)
      stdout.println(`Total: ${result}`)
Other ways to ask this
  • When do I use the arrow <- vs the colon-equals := in EK9?
  • My variable already exists but <- creates a new one — help!
  • EK9 variable shadowing with <- operator

Coming from another language?

Python: rebinding with = is always reassignment. Java: type declaration vs assignment. EK9: <- declares, := reassigns — using <- twice creates shadowing.

Keywords: scope, error, arrow, declare, variable, assign, shadow, rebind