Declaration, assignment and assign-if-unset guards

The complete source of flowControl_guard_forms.ek9, compiled by the EK9 compiler. Shown on flowControl.html.

#!ek9
defines module site.flowControl.guardforms

  defines constant
    THRESHOLD <- 10
    CACHE_LIMIT <- 100

  defines class

    Record
      valid as Boolean: false

      Record()
        -> valid as Boolean
        this.valid: valid

      default Record()

      isValid() as pure
        <- rtn as Boolean: valid

      default operator ?

  defines function

    getOptional()
      <- rtn as Integer: 12

    fetchData()
      <- rtn as Record: Record(true)

    compute()
      <- rtn as Integer: 120

  defines program

    GuardForms()
      stdout <- Stdout()

      if value <- getOptional() with value > THRESHOLD
        stdout.println(`declared ${value}`)

      existing <- Record()
      if existing := fetchData() then existing? and (existing.isValid())
        stdout.println("fetched a valid record")

      cache <- Integer()
      if cache :=? compute() with cache > CACHE_LIMIT
        stdout.println(`cached ${cache}`)

Download flowControl_guard_forms.ek9

Output

declared 12
fetched a valid record
cached 120