What are the three assignment operators in EK9 and when do I use each?
← Getting Started · Ref: Q965
EK9 has assignment operators for declaration and reassignment. EK9 separates declaration from reassignment with distinct operators:
<- DECLARATION WITH TYPE INFERENCE: Creates a NEW variable, compiler infers the type.
name <- "Steve" creates variable 'name' (inferred as String) count <- 0 creates variable 'count' (inferred as Integer) stdout <- Stdout() creates variable 'stdout' (inferred as Stdout)
:= or : or = ASSIGNMENT: All three are interchangeable for reassignment.
name := "Alice" changes existing 'name' to "Alice" name: "Alice" same effect — : is shorthand for := name = "Alice" same effect — = also works
With EXPLICIT TYPE declaration, use : or := or = with a type:
age as Integer: 30 declares 'age' as Integer with value 30 age as Integer := 30 same effect age as Integer = 30 same effect
:=? GUARDED ASSIGNMENT: Only assigns if the target is currently UNSET.
name :=? "Default" assigns "Default" ONLY if name is unset name :=? "Other" does nothing — name is already set
KEY RULES:
- <- is declaration with type inference (used once per variable)
- :=, :, = are interchangeable for reassignment and explicit type declaration
- :=? is safe for conditional initialization
EK9 makes this distinction at the operator level — <- always means 'new variable', := always means 'update existing'.
Example
defines module qa.gettingstarted.assignmentops defines program AssignmentOpsDemo() stdout <- Stdout() // <- DECLARATION: creates new variable greeting <- "Hello" stdout.println(`After <-: ${greeting}`) // := ASSIGNMENT: updates existing variable greeting := "Hi there" stdout.println(`After :=: ${greeting}`) // := again on same variable — fine, it exists greeting := "Hey" stdout.println(`After := again: ${greeting}`) // :=? GUARDED: only assigns if unset nickname <- String() stdout.println(`Before :=?: nickname is ${nickname?}`) nickname :=? "Buddy" stdout.println(`After :=? on unset: ${nickname}`) nickname :=? "Pal" stdout.println(`After :=? on set: ${nickname}`) // Practical example: building a configuration host <- "localhost" port <- 8080 host := "production.example.com" port := 443 stdout.println(`Config: ${host}:${port}`)
Other ways to ask this
- What is the difference between <- and := in EK9?
- When do I use <- vs := vs :=? in EK9?
- How do declaration and assignment differ in EK9?
- What does <- mean in EK9?
- What does := mean in EK9?
- What does :=? mean in EK9?
Coming from another language?
Go separates declaration (:=) from assignment (=), EK9 does the same with <- and :=. Java and Python use = for both (ambiguous). Kotlin uses val/var keywords, EK9 uses operators.
Keywords: reassignment, assignment, variable creation, guarded, declaration