Variables
Assignment
Section titled “Assignment”Assigning to a name creates the variable. Kiwi is dynamically typed, so the same variable can hold a different type later.
count = 10price = 20.5greeting = "Hello"items = [1, 2, 3]
count = "ten" # now a stringprintln count # tenReading a variable that was never assigned is an error:
println missing # VariableUndefinedError: The variable has not been declared: 'missing'Assignment is an expression, so it can be chained:
a = b = c = 0println [a, b, c] # [0, 0, 0]Compound assignment operators (+=, -=, *=, ||= and so on) are listed under Operators.
Multiple assignment
Section titled “Multiple assignment”Separate names with commas to assign several at once. The right-hand side can be a list of expressions or a single list value, which is unpacked.
a, b, c = 10, 20, 30println "${a} ${b} ${c}" # 10 20 30
fn bounds() [0, 100]end
low, high = bounds()println high # 100
x, y = 1, 2x, y = y, x # swapprintln [x, y] # [2, 1]Names without a matching value are set to null:
first, second, third = [1, 2]println third # nullvar declarations
Section titled “var declarations”var declares a variable explicitly, optionally with a type hint. It is never required, but it documents intent and gives typed variables a starting value.
var greeting = "Hello"var count: integer = 0var ratio: float = 0.5var maybe: string? = nullWith a type hint and no initializer, the variable starts at that type’s zero value:
| Hint | Starts as |
|---|---|
integer | 0 |
float | 0.0 |
string | "" |
boolean | false |
list | [] |
hashmap | {} |
var total: integervar names: list
total += 5names.push("kiwi")println [total, names] # [5, ["kiwi"]]var name with neither an initializer nor one of the hints above starts as null:
var resultprintln result # nullGroup several declarations in parentheses:
var (count: integer = 0, label = "items", scale: float)println [count, label, scale] # [0, "items", 0]Type hints on variables are documentation only; Kiwi does not check them at runtime. See Type Hints.
Constants
Section titled “Constants”const declares a value that can’t be reassigned. Constant names must use only upper-case letters and underscores.
const MAX_RETRIES = 3const API_URL = "https://example.com"
println MAX_RETRIES # 3Reassigning a constant is an error:
const LIMIT = 10LIMIT = 20 # InvalidOperationError: Cannot reassign constant 'LIMIT'.const protects the binding, not the value. A constant list or hashmap can still be modified in place:
const NAMES = ["kiwi"]NAMES.push("mango")println NAMES # ["kiwi", "mango"]Where variables live
Section titled “Where variables live”Variables assigned at the top level of a script are global. Variables first assigned inside a function belong to that call. See Scoping for the full rules, including closures and struct instance variables.