How do I declare a variable in EK9?

← Getting Started · Ref: Q1000

Use the <- operator to declare a variable. The compiler infers the type from the value.

  greeting <- "Hello"        creates a String variable
  count <- 0                 creates an Integer variable
  price <- 19.99             creates a Float variable
  active <- true             creates a Boolean variable
  names <- List() of String  creates a List of String

The <- operator means 'create this variable with this value'. It can only be used once per variable name. After declaration, use := to update the value:

  greeting <- "Hello"        declaration (first time)
  greeting := "Hi there"     update (every time after)

With explicit type:

  age as Integer: 30         declares 'age' as Integer with value 30
  name as String: "Steve"    declares 'name' as String

Example

defines module qa.gettingstarted.declarefirstvariable

  defines program

    DeclareFirstVariable()
      stdout <- Stdout()

      // Declare variables with <- (type inferred)
      greeting <- "Hello, EK9"
      count <- 42
      price <- 19.99
      active <- true

      stdout.println(greeting)
      stdout.println(`Count: ${count}`)
      stdout.println(`Price: ${price}`)
      stdout.println(`Active: ${active}`)

      // Update with := after declaration
      greeting := "Welcome to EK9"
      stdout.println(greeting)

      // Declare with explicit type
      language as String: "EK9"
      stdout.println(language)

Common mistakes

E50001 — Use <- to declare a new variable; using := first means the variable was never declared, so it is unresolved and triggers E50001. See ek9 -h E50001 for details.

Incorrect:

      greeting := "Hello, EK9"

Correct:

      greeting <- "Hello, EK9"
Other ways to ask this
  • What is the syntax for creating a variable in EK9?
  • How do I create and initialise a variable?
  • Show me the basic variable declaration syntax

Coming from another language?

EK9 uses <- for declaration with type inference. Unlike Java/Python where = does both declaration and assignment, EK9 separates them.

Keywords: first, variable, declare, arrow, create, basics