How do I build up a String with '+=' in EK9?

← Common String Operations · Ref: Q2251

Start the String from "" - the empty String - and append to it with '+='.

  joinWords()
    -> words as List of String
    <- sentence as String: ""
    for word in words
      if sentence is not empty
        sentence += " "
      sentence += word

WHY NOT String()
'String()' makes a String that is present but UNSET - it has no value yet, not even an empty one. '+=' on an unset String keeps it unset (an operator never invents the missing value), so every word would be lost and the result would still be unset. The compiler is sure of both facts here, so it reports the line as E08096 instead of letting the program quietly produce nothing:

  sentence <- String()
  for word in ["Hello", "World"]
    sentence += word    //E08096: 'sentence' is always unset here

"" IS set: its value is known, it simply has no characters. That is the value to build on - the same as starting a sum from 0 (see Q2252).

See Q2253 for why 'count <- Integer()' then 'count++' is reported, Q936 for the '?' set check, and Q880 for what EK9 does not have (null).

Example

#!ek9
defines module qa.stringops.buildupfromempty

  defines function

    joinWords()
      -> words as List of String
      <- sentence as String: ""
      for word in words
        if sentence is not empty
          sentence += " "
        sentence += word

  defines program

    BuildUpStringDemo()
      stdout <- Stdout()
      words <- ["build", "it", "up"]
      stdout.println(joinWords(words))

      summary <- ""
      summary += "words: "
      summary += $words.length()
      stdout.println(summary)

Common mistakes

E08096 — String() makes an unset String and '+=' keeps an unset String unset, so every word is lost. Start from "", which is set. See ek9 -h E08096 for details.

Incorrect:

<- sentence as String: String()

Correct:

<- sentence as String: ""
Other ways to ask this
  • How do I accumulate text in a loop in EK9?
  • Why does 'text <- String()' then 'text += word' not compile?
  • What should a String start from before I append to it?
  • How do I concatenate words into one String in a loop?

Coming from another language?

Java: StringBuilder sb = new StringBuilder(); or String s = ""; s += word; - a String declared without a value is null and 's += word' gives "nullword". Python: s = "" then s += word. Kotlin: buildString { append(word) }. EK9: 'sentence <- ""' then 'sentence += word'; 'String()' is an UNSET String, which '+=' keeps unset, so the compiler reports E08096.

Keywords: +=, E08096, String, String(), StringBuilder, accumulate, append, build up, concatenate, empty string, unset