The language / Variables
Start here01
The language02
- 01The basics
- 02Values and numbers
- 03Variables
- 04Calls and expressions
- 05Conditions and loops
- 06Strings
- 07Arrays and hashes
- 08Classes and records
- 09Traits and enums
- 10Blocks
- 11Methods
- 12Imports and exports
- 13Foreign files
- 14Failures
Programs and the world03
- 01Files, input and output
- 02JSON, time, URLs and random numbers
- 03Html and forms
- 04Templates: Ochre
- 05Built-in methods
Kiln04
02 The language / 03
Variables
Every variable has a name and a type that never changes, and it holds nil only where its type says so.
Variables are how a program keeps values and refers to them later. Each one is declared before it is used, and says up front whether it may change. Rules like these let a reader trust what a name holds from the line that declares it, and let Hematite find mistakes, such as a typo in a name or a value that might be missing, before the program runs.
Declaring a variable
Every variable is declared before it is used, with a starting value. const declares one that never changes, and var one that may. To change a var later, write name = value, with no keyword:
const price = 100 # never changes
var total = price # may change
total = total + 25 # changing a var: no keywordUse const unless the variable really needs to change. A reader who sees const then knows the value stays the same, without reading any further.
name = value only changes a var that already exists. It never creates a variable, so a typo in a name is caught as an error instead of quietly making a new variable. The other mistakes here are caught too: a var with no starting value, and changing a const.
var total = 0
totl = total + 5 # error: undefined variable 'totl'; declare it first with 'var totl = ...' or 'const totl = ...'
var count # error: expected '=' after 'var count', found end of line; every variable starts with a value
const limit = 10
limit = 20 # error: 'limit' is a const and can't be changed; declare it with 'var' if it needs to changestatic: values for the whole file
A file's top-level code, its vars, consts and other statements, is its script: it runs from top to bottom. A static belongs to the file itself instead. Methods can use it, and other files can import it:
static TAX_RATE = 0.25
def with_tax(price: Float): Float
return price * (1 + TAX_RATE)
end
print(with_tax(100.0)) # prints 125.0Statics are set up before the script runs, one after another, in the order they are written. Two things follow from that. The script and every method can use any static, wherever it is in the file. And a static's value can only use what exists by then: plain values, the statics above it, and methods. The script's vars and consts don't exist yet, since they only appear once the script runs.
var base = 2
static DOUBLE = base * 2 # error: 'base' is a var of the file's script, which runs after the statics are set up; a static can only use values, other statics and methods
static A = B + 1 # error: 'B' is a static set up after this one: statics are set up in order, each file's from the top and after those of the files it imports, so a static can only use the statics set up before it
static B = 1Statics are declared only at the top level of a file, never inside a block or method, and they never change. Use static when a method or another file needs the value; otherwise use const.
Types never change
A variable's type is set by its first value, and it never changes. A var that starts as an Int only ever holds Ints:
var n = 10
n = n / 2 # error: 'n' holds an Int and can't hold a Float
var sum = 0.0 # will hold Floats, so start with a Float
sum = sum + 1 # fine: Int + Float gives a FloatInt and Float are different types, and / always gives a Float. So a variable that receives the results of division must start as a Float, like sum above. This is checked before running, even in code that never runs.
Writing the type
You may write the type after the name, following a colon. It is never required, except to start a var as nil (see below).
const limit: Int = 10
var ratio: Float = 0.5
var done: Boolean = falseThe types are Int, Float, Boolean and String; arrays, such as [Int], [String?] and [[Float]]; hashes, such as {String: Int} and {Int: [String]}; and classes, such as Account, [Account] and Account?.
Writing the type never converts the value. The value must already have that type, so 0 can't start a Float; write 0.0 (or convert it yourself):
var total: Float = 0 # error: 'total' is declared as Float but its value is an Int
var sum: Float = 0.0
print(sum) # prints 0.0nil and optional types
nil means "no value". It is the only such value: there is no null and no undefined.
A variable can only hold nil if its type ends in ?, which means "this type, or nil". Use it for a value you don't have yet, such as the answer to a search that hasn't finished:
var found: Int? = nil
var i = 0
while i < 10
if i * i > 50 and found == nil
found = i
end
i = i + 1
end
print(found) # prints 8Int? accepts Ints and nil, and nothing else: found = 2.5 is an error. A plain Int never accepts nil, so wherever the type has no ?, you know there is a value.
A var without a type can't start as nil, because nothing would say what it holds later:
var user = nil # error: 'user' can't start as nil without a type; declare what it will hold, e.g. 'var user: Int? = nil'A const may be nil without a type, since it never changes.
Checking for nil
A value that might be nil can't be used as if it were there until the code checks it. That covers a T? variable, and also what .get and find give (see arrays and hashes). Here age comes from .get, so it can't be added to until it is checked:
const ages = {"Ada": 36}
const age = ages.get("Ada")
print(age + 1) # error: age might be nil here; check it first, like 'if age != nil'
if age != nil
print(age + 1) # prints 37
endAfter a check, Hematite knows the value is a T. These count as a check:
- Inside
if x != nil,xis aT. So it is in theelseofif x == nil. - After an
if x == nilwhose body ends withreturn,breakorcontinue,xis aTfor the rest of the block. - After an
if x == nilwhose body givesxa value,xis aT. - On the right of
andafterx != nil, and on the right oforafterx == nil.notturns a check around.
The first is the plain if. The second is an early return: deal with nil first, and the rest of the method can rely on the value. The last works because the right side of and and or only runs when the left side hasn't already decided the answer:
def next_age(age: Int?): Int
if age == nil
return 0
end
return age + 1 # age is an Int after the early return
end
print(next_age(36)) # prints 37
print(next_age(nil)) # prints 0
var best: Int? = nil
const scores = [3, 9, 4]
scores.each do (score)
if best == nil or score > best
best = score
end
end
print(best) # prints 9Variables, parameters, fields (self.total, account.owner) and a hash's .get(key) after .has(key) (see hashes) can be checked. Anything else, like an array element or a method's result, goes into a const first, and the const is checked:
const names: [String?] = ["Ada", nil]
const first = names[0]
if first != nil
print(first.length) # prints 3
endA check holds until something in the checked code changes what was checked: assigning the variable or field, changing the hash (.set, .remove), assigning the key's variable, or calling a method that changes that field. A method only counts for the fields it changes, itself or through the methods it calls. Loops and blocks run their body more than once, so a check made before them doesn't hold inside a body that changes the value. When a check stops holding, the error names the line that ended it:
var x: Int? = 5
if x != nil
x = nil
print(x + 1) # error: x might be nil here, since line 4 changes x; check it again after that line, like 'if x != nil'
endThe other way round is an error too. Comparing a value with nil when its type can't be nil is a mistake, since the answer is always the same:
const count = 3
print(count == nil) # error: count is never nil here, since it's an Int; the comparison is always the sameScope: where a variable exists
A variable exists from its declaration to the end of the block that contains it. Blocks are the bodies of if, else if, else and while, and the file itself is the outermost block. Inner blocks can use and change variables from outer blocks.
A name can't be declared while a variable with that name is visible, not even in an inner block. So a name never hides another one:
const x = 1
if true
const x = 2 # error: 'x' is already declared at line 1, column 1; choose a different name
endSibling blocks may reuse a name, and so may each time round a loop. A variable declared inside a block is gone after its end; to use a value after the block, declare the variable before it:
if true
const inside = 1
end
print(inside) # error: undefined variable or method 'inside'Checked before running
Names and types are checked before anything runs. A program with one of these mistakes doesn't start at all, even if the mistake is in a branch that would never run:
- undeclared names, declaring a name twice, and changing a
const; - values that don't fit their variable, parameter, return type, field, array or hash;
- conditions that aren't
trueorfalse, and operators used on the wrong types ("a" + 1,"a" < "b",1 == "1"); - methods and fields that don't exist, and private or readable fields used from outside;
- values that might be
nil, used without a check.
Some errors can only happen while running, because they depend on the values: dividing by zero, numbers too big for an Int, reading past the end of an array, converting text like Int("abc"), and too many nested calls.
One more rule about names: the names of built-in methods can't be variable names.
var print = 1 # error: 'print' is a built-in method and can't be used as a variable nameDeclarations and assignments are statements
Declaring a variable and changing one are statements, one per line, so a line that does two at once is an error:
const x = y = 0 # error: assignment must be a statement on its own line, not part of an expressionThey are always a whole statement, never part of an expression or a call:
const y = (x = 1) # error: assignment must be a statement on its own line, not part of an expression
print(x = 1) # error: assignment must be a statement on its own line, not part of an expressionOnly something that can hold a value, a variable, an element like items[0] or a field, may stand on the left of =:
1 = x # error: only a variable or an element like 'items[0]' can be on the left side of '='
x + 1 = 2 # error: only a variable or an element like 'items[0]' can be on the left side of '='