Chapter 2: declaring and changing values, typed

Chapter 2 shows every way to declare a value and to change one. There is no tool that writes a declaration for you - typing them is the exercise - so the IDE writes only the program's shell, and you type the body, comments included. To play it in the IDE: Help > Lessons > Getting Started with EK9…, or ek9 -ide -lesson book-declarations.

The EK9 IDE as the lesson opens

What you'll build

The lesson builds this program from a file holding only its module line - the finished file, as the book prints it.

#!ek9
defines module book.declarations

  defines program
    Show()
      stdout <- Stdout()

      //Inferred declaration (the everyday form)
      a <- 21

      //Explicit type; ':', '=' and ':=' are all valid initialisers
      b as Integer: 21
      c as Integer = 21
      d as Integer := 21

      //Explicit type, no starting value (must be set before use)
      e as Integer?

      stdout.println(`a=${a} b=${b} c=${c} d=${d}`)

      //Changing an existing value: ':=', '=' and ':' all reassign
      a := 1
      a = 2
      a: 3
      stdout.println(`a now ${a}`)

      //Assign-if-unset: only sets when currently unset
      e :=? 99
      stdout.println(`e set? ${e?}  e now ${e}`)

Step 1: The program's shell

Choose Code > New Construct > Program…

The EK9 IDE once this is done: Choose Code > New Construct > Program…

Show is the program's name. Type it and choose Preview.

The EK9 IDE just before choosing Preview: Show is the program's name

The preview shows Show about to be written. Choose Apply.

The EK9 IDE just before choosing Apply: The preview shows Show about to be written

Step 2: The body, typed

Select the stub, from ready <- true down to its //AI line, and type the body exactly as the chapter shows it. Saves when typed.

The EK9 IDE once this is done: Select the stub, from ready <- true down to its //AI line, and type the body exactly as the chapter shows it

Step 3: Run it

Choose Run > Run Program…

The EK9 IDE once this is done: Choose Run > Run Program…

The project's only program is already chosen. Choose Run.

a=21 b=21 c=21 d=21, then a now 3, then e set? true e now 99 - the unset e took 99 because it was unset. Choose Close.

The EK9 IDE just before choosing Close: a=21 b=21 c=21 d=21, then a now 3, then e set? true e now 99 - the unset e took 99 because it was unset

The result

Declarations.ek9 now reads exactly as chapter 2 of Getting Started with EK9 shows it: the same value declared four ways, an unset one, three ways to reassign and the assign-if-unset form. The shell was the tool's (ek9_add_program); the declarations are yours.

The EK9 IDE when the lesson has finished

Where this lesson comes from