Is an empty List set or unset in EK9? What about an empty Dict?

← Collections and Data Structures · Ref: Q1019

Empty collections are ALWAYS SET in EK9. Creating a collection makes it set, even with zero items.

  emptyList <- List() of String
  emptyList?                         true - empty list IS set
  emptyDict <- Dict() of (String, Integer)
  emptyDict?                         true - empty dict IS set

This is different from primitives where an uninitialised value is unset:

  unsetName <- String()
  unsetName?                         false - no value assigned

WHY COLLECTIONS ARE ALWAYS SET:

An empty collection is a valid, meaningful state - it means 'I looked and found nothing.' An unset collection would mean 'I haven't looked yet.' EK9 keeps this distinction clear.

CHECK EMPTINESS WITH 'is empty':

  if myList is empty
    stdout.println("List has no items")
  if myList is not empty
    stdout.println("List has items")

Do not confuse empty (no items) with unset (no value). An empty list is set but empty.

Example

defines module qa.collections.alwaysset

  defines function

    fetchNames()
      -> searchTerm as String
      <- rtn as List of String: List() of String

      if searchTerm == "team"
        rtn += "Alice"
        rtn += "Bob"

  defines program

    CollectionsAlwaysSetDemo()
      stdout <- Stdout()

      //Fetch with results
      teamNames <- fetchNames("team")
      stdout.println(`Team set?: ${teamNames?}`)
      if teamNames is not empty
        stdout.println(`Team has ${teamNames.length()} members`)

      //Fetch with no results - still SET, just empty
      unknownNames <- fetchNames("unknown")
      stdout.println(`Unknown set?: ${unknownNames?}`)
      if unknownNames is empty
        stdout.println("No results found - but list IS set")

      //Compare with unset primitive
      unsetName <- String()
      stdout.println(`Unset string set?: ${unsetName?}`)

Common mistakes

E50060 — EK9 uses 'is empty' / 'is not empty', not a '.isEmpty()' method. See ek9 -h E50060 for details.

Incorrect:

      if unknownNames.isEmpty()

Correct:

      if unknownNames is empty
Other ways to ask this
  • Are empty collections considered set in EK9?
  • What is the difference between an empty list and an unset list?
  • When I create List() of String, is it set?

Coming from another language?

In EK9, creating a collection makes it set immediately. Empty is not unset. Use 'is empty' or 'is not empty' to check for zero items.

Keywords: empty, collection, unset, always set, dict, set, list