What should a counter or a running total start from in EK9?
← Operators and Expressions · Ref: Q2252
Start a counter or a sum from 0, and a product from 1 - a literal, which is a SET value - then change it with '++', '+=' or '*='.
total <- 0 for amount in amounts total += amount
count <- 0 for amount in amounts if amount > threshold count++
WHY NOT Integer()
'Integer()' makes an Integer that is present but UNSET - no value yet. '+=', '-=', '*=', '/=', '++' and '--' on an unset value keep it unset whatever is added: the operator never invents the missing starting value. So a total started from 'Integer()' stays unset however many amounts are added. The compiler is sure of that here, so it reports E08096 at the '+=' rather than let the loop run for nothing:
total <- Integer() for amount in [10, 20, 30] total += amount //E08096: 'total' is always unset here
The same holds for Float (start from 0.0), Duration (PT0S), Millisecond (0ms), String ("", see Q2251) and every other built-in type with these operators.
The compiler reports it only when it is SURE: a value that came from a function call may be set, so 'total <- supplied()' then 'total += 1' is never reported. See Q2253, and Q2251 for building up a String.
Example
#!ek9 defines module qa.operators.countandsumfromzero defines constant THRESHOLD <- 5 defines program CountAndSumDemo() stdout <- Stdout() amounts <- [2, 4, 6, 9] total <- 0 for amount in amounts total += amount stdout.println(`total: ${total}`) count <- 0 for amount in amounts if amount > THRESHOLD count++ stdout.println(`above threshold: ${count}`) product <- 1 for factor in 1 ... 5 product *= factor stdout.println(`product: ${product}`)
Common mistakes
E08096 — Integer() makes an unset Integer and '+=' keeps an unset Integer unset, so the total never gets a value. Start from 0. See ek9 -h E08096 for details.
Incorrect:
total <- Integer()
Correct:
total <- 0
E08096 — '++' on an unset Integer keeps it unset, so the count never starts. Start from 0. See ek9 -h E08096 for details.
Incorrect:
count <- Integer()
Correct:
count <- 0
E08096 — '*=' on an unset Integer keeps it unset. A product starts from 1. See ek9 -h E08096 for details.
Incorrect:
product <- Integer()
Correct:
product <- 1
Other ways to ask this
- How do I sum a List of Integers with '+=' in EK9?
- Why is 'total <- Integer()' then 'total += amount' an error?
- How do I count matches in a loop with '++'?
- Where should a product start before '*='?
Coming from another language?
Java: int total = 0; an Integer total left null throws NullPointerException on 'total += x'. Python: total = 0. Kotlin: var total = 0. EK9: 'total <- 0'. 'Integer()' is an UNSET Integer, which '+=' keeps unset, so the compiler reports E08096.
Keywords: *=, ++, +=, E08096, Integer(), accumulate, counter, start from zero, sum, total, unset