My variable already exists but <- creates a new one — help!

← Getting Started · Ref: Q972

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

PATTERN:

  name <- "Steve"     FIRST TIME: <- creates name
  name := "Alice"     AFTER: := updates name
  name := "Bob"       AFTER: := updates name again

The compiler ENFORCES this:
- Using := before <- is an error (variable does not exist yet)
- Using <- twice on the same name is an error (already declared)

Also: ':=' and ':' and '=' are all interchangeable for reassignment.

  name := "Alice"   same as
  name: "Alice"     same as
  name = "Alice"

Example

defines module qa.gettingstarted.declarethenassign

  defines program

    DeclareThenAssignDemo()
      stdout <- Stdout()

      // <- creates the variable (FIRST TIME)
      greeting <- "Hello"
      stdout.println(greeting)

      // := updates it (EVERY TIME AFTER)
      greeting := "Hi there"
      stdout.println(greeting)

      // := again — still updating
      greeting := "Hey"
      stdout.println(greeting)

      // : is shorthand for :=
      greeting: "Yo"
      stdout.println(greeting)

      // Another variable: <- first, then :=
      counter <- 0
      counter := counter + 1
      counter := counter + 1
      stdout.println(`Counter: ${counter}`)

Common mistakes

E50001 — The first use of a variable must be '<-' to create it; using ':=' on a name that does not exist yet is not resolved. See ek9 -h E50001 for details.

Incorrect:

greeting := "Hello"

Correct:

greeting <- "Hello"
Other ways to ask this
  • When do I use <- vs := in EK9?
  • I keep mixing up <- and := in EK9
  • What is the rule for <- vs := in EK9?

Coming from another language?

Unlike Java and Python where = does both declaration and reassignment, EK9 separates them: <- declares a new variable, := updates an existing one. This prevents accidental shadowing.

Keywords: first time, create, assign, update, arrow, declare