Variables store values. Declare them with var or const, a name, an optional type and an initial value.
Both var and const require an initial value. Use null if you don’t have a value yet:
var
var declares a mutable variable. Reassign it with =:
There’s no compound assignment (+=) and no increment operator (++). Write count = count + 1 instead.
const
const declares a variable that can’t be reassigned:
const only prevents rebinding the name. If a const holds an object or list, you can still change its contents:
Contract parameters are const variables.
Type inference
When you leave out the type, it’s inferred from the initial value:
Declare the type explicitly when the inferred type is too narrow. For example, var total = 0 infers int32, so assigning 9.99 to it later is an error. Write var total: decimal = 0 instead.
Types never change
A variable’s type is fixed when it’s declared. Every reassignment is checked against that type, with numeric promotion applied:
Assignments to object properties and list elements aren’t type-checked, because object is untyped and list contents can be changed in place:
Assignment targets
You can assign to:
- A
var variable: name = value
- An object property:
obj.prop = value. If the property doesn’t exist, it’s added.
- A list element:
list[i] = value. The index must be an integer within the list’s bounds.
Scope
Each if, else if and else body is its own scope. Variables declared inside a body aren’t visible after it:
To use a value after the if, declare the variable before it and assign it inside:
No redeclaration or shadowing
A name can only be declared once. This includes shadowing: declaring a name inside an if body that already exists in an enclosing scope is an error.