Skip to the page
The language / Variables

Start here01

The language02

Programs and the world03

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:

variables-const-and-var.hem
const price = 100 # never changes
var total = price # may change

total = total + 25 # changing a var: no keyword

Use 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.

declaration-mistakes.hem
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 change

static: 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-values-for-the-whole-file.hem
static TAX_RATE = 0.25

def with_tax(price: Float): Float
  return price * (1 + TAX_RATE)
end

print(with_tax(100.0)) # prints 125.0

Statics 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.

static-order.hem
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 = 1

Statics 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:

types-never-change.hem
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 Float

Int 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).

writing-the-type.hem
const limit: Int = 10
var ratio: Float = 0.5
var done: Boolean = false

The 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):

type-must-match.hem
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.0

nil 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:

nil-and-optional-types.hem
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 8

Int? 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:

untyped-nil.hem
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:

checking-for-nil.hem
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
end

After a check, Hematite knows the value is a T. These count as a check:

  • Inside if x != nil, x is a T. So it is in the else of if x == nil.
  • After an if x == nil whose body ends with return, break or continue, x is a T for the rest of the block.
  • After an if x == nil whose body gives x a value, x is a T.
  • On the right of and after x != nil, and on the right of or after x == nil. not turns 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:

early-return-and-or-checks.hem
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 9

Variables, 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:

checking-an-element.hem
const names: [String?] = ["Ada", nil]
const first = names[0]

if first != nil
  print(first.length) # prints 3
end

A 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:

check-ended-by-assignment.hem
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'
end

The 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:

never-nil.hem
const count = 3

print(count == nil) # error: count is never nil here, since it's an Int; the comparison is always the same

Scope: 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:

scope-where-a-variable-exists.hem
const x = 1

if true
  const x = 2 # error: 'x' is already declared at line 1, column 1; choose a different name
end

Sibling 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:

out-of-scope.hem
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 true or false, 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.

built-in-name.hem
var print = 1 # error: 'print' is a built-in method and can't be used as a variable name

Declarations 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:

chained-assignment.hem
const x = y = 0   # error: assignment must be a statement on its own line, not part of an expression

They are always a whole statement, never part of an expression or a call:

assignment-in-expression.hem
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 expression

Only something that can hold a value, a variable, an element like items[0] or a field, may stand on the left of =:

left-side-of-assignment.hem
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 '='