Skip to the page
The language / Classes and records

Start here01

The language02

Programs and the world03

Kiln04

02 The language / 08

Classes and records

Classes for things that do something, records for plain data.

Classes and records are how you make types of your own. A class bundles data (its fields) with the methods that work on it, and decides what the rest of the program may read or change. A record is plain data, whose fields anyone can read and nothing can change. Both are values, like arrays and hashes, and that shapes how you change them.

Classes

A class describes objects: the fields they hold and the methods that work on them. This account has a field for each kind of access, a few public methods, and one private one:

account.hem
class Account
  readable const owner: String
  readable var balance: Float = 0.0

  writable var nickname: String = ""

  var history: [Float] = []

  def deposit(amount: Float)
    self.balance = self.balance + amount

    self.history.push(amount)
  end

  def summary(): String
    return "#{self.owner} has #{self.balance} after #{self.deposits()} deposits"
  end

  private def deposits(): Int
    return self.history.length
  end
end

var account = new Account(owner: "Ada")

account.deposit(50.0)
print(account.summary()) # prints Ada has 50.0 after 1 deposits
print(account.balance)   # prints 50.0

account.nickname = "Ace"

print(account) # prints Account(owner: "Ada", balance: 50.0, nickname: "Ace")

A class is defined at the top level of a file, and can be used anywhere in the file. Its name starts with an uppercase letter. The class body holds fields first, then methods, and nothing else.

Fields

Every field is declared with a type. What the rest of the program may do with it is written in front, so a class's fields show at a glance what outside code can see and touch:

FieldOutside code mayInside, the class may
readable const owner: Stringreadread
readable var balance: Float = 0.0readread and change
writable var nickname: String = ""read and changeread and change
var history: [Float] = []nothingread and change
const kind: String = "basic"nothingread

Without readable or writable, a field is private. writable const is an error, since a const can't be changed.

A private field needs a default value, because new can't set it. A default may use values, statics and methods, and it is computed for each new object.

Outside code can't change a readable field, not even its contents: account.history.push(1) is an error unless history is writable. Changes go through the class's own methods, which keeps the class in charge of its data:

readable-not-writable.hem
class Account
  readable var balance: Float = 0.0
end

var account = new Account()

print(account.balance) # prints 0.0

account.balance = 1000000.0 # error: 'balance' is readable in Account, not writable; change it through a method of Account

Creating objects

new ClassName(field: value, ...) creates an object. Values are named, so their order doesn't matter:

creating-objects.hem
class Point
  writable var x: Int
  writable var y: Int = 0
end

const a = new Point(x: 1, y: 2)
const b = new Point(y: 2, x: 1)
const c = new Point(x: 5)

print(a == b) # prints true
print(c)      # prints Point(x: 5, y: 0)

const d = new Point(y: 1) # error: new Point(...) needs a value for x

Every readable or writable field without a default must be given, and each value must match the field's type. A readable or writable field with a default may be given too: the default is only its starting value when new doesn't give one. Private fields can't be given; they always start with their default.

That includes readable fields. readable means outside code can't change the field once the object exists, and giving its starting value in new is not a change, so it's allowed:

readable-given-in-new.hem
class Account
  readable var balance: Float = 0.0
end

const empty = new Account()
const funded = new Account(balance: 10.0)

print(empty.balance)  # prints 0.0
print(funded.balance) # prints 10.0

Inside methods: self

Inside a class's methods, the object itself is self, and you reach its fields and methods through it:

WriteMeans
self.balancethe object's field balance
self.balance = valuechange the field (only a var field)
self.deposits()call one of the object's own methods
self.totalcall an own method that takes no arguments

A bare name is never a field or an own method. As in every method, it is a parameter, a local variable, a static, or a top-level method. So on any line you can tell which names belong to the object: they're the ones after self..

Methods

Methods are public: outside code calls them as account.deposit(10.0). private def makes a method callable only from the class's own methods, as self.name(...).

A method that changes self (assigns to a field, pushes onto one, or calls another changing method) can only be called on a var. An object is a value, held by its variable, so changing the object changes that variable, and a const never changes:

changing-method-needs-var.hem
class Counter
  readable var count: Int = 0

  def increment()
    self.count = self.count + 1
  end
end

var counter = new Counter()

counter.increment()
print(counter.count) # prints 1

const frozen = new Counter()

frozen.increment() # error: 'frozen' is a const and can't be changed; declare it with 'var' if it needs to change

What a call changes is decided by what it's called on, never by the method's name: a class's own push, or int, changes only what its body changes, so one that just reads needs no var.

A changing method's arguments run first. The method then changes the object as they left it. Here withdraw_all() empties the account while the arguments are worked out, and deposit then puts the 10 back:

arguments-run-first.hem
class Account
  readable var balance: Int = 0

  def deposit(amount: Int)
    self.balance = self.balance + amount
  end

  def withdraw_all(): Int
    const all = self.balance

    self.balance = 0

    return all
  end
end

var account = new Account()

account.deposit(10)
account.deposit(account.withdraw_all())
print(account.balance) # prints 10

Objects are values

Like arrays and hashes, objects are copied when assigned or passed. Changing a copy never changes the original:

objects-are-values.hem
class Counter
  readable var count: Int = 0

  def increment()
    self.count = self.count + 1
  end
end

var a = new Counter()
var b = a

b.increment()
print(a.count) # prints 0
print(b.count) # prints 1

From the moment it's assigned, b is a counter of its own. No other variable shares it, so a change to an object only ever shows in the variable you made it through.

Objects inside arrays and fields can be changed in place, through the array or field that holds them:

change-in-place.hem
class Counter
  readable var count: Int = 0

  def increment()
    self.count = self.count + 1
  end
end

var counters = [new Counter(), new Counter()]

counters[1].increment()
print(counters[1].count) # prints 1

Two objects are equal (==) when they are of the same class and all their fields are equal.

Statics: the class's own values and methods

static means the same in a class as at the top of a file: it belongs to the definition, not to something running. A class's statics belong to the class itself, not to any of its objects. Code uses them through the class's name, also inside the class:

class-statics.hem
class Account
  static LIMIT = 1_000
  readable const owner: String
  readable var balance: Int = 0

  static def opened_by(owner: String): Account
    return new Account(owner: Account.title() + owner)
  end

  private static def title(): String
    return "Ms. "
  end

  def can_deposit(amount: Int): Boolean
    return self.balance + amount <= Account.LIMIT
  end
end

const ada = Account.opened_by("Ada")

print(ada.owner)              # prints Ms. Ada
print(Account.LIMIT)          # prints 1000
print(ada.can_deposit(5_000)) # prints false
print(Account.title())        # error: 'title' is private in Account; only Account's own methods can call it, as Account.title(...)
print(Account.balance)        # error: 'balance' belongs to each Account object, not to the class; use it on an object, like account.balance
  • Statics come before the fields: static NAME = value for a value, static def for a method. Static values follow the rules for statics at the top of a file: set up in order before the script runs, using only values, statics and methods, and never changing.
  • A static method has no object, so it has no self. It's the place for ways to make objects, like Account.opened_by(...).
  • private static def can only be called by the class's own methods. Static values can always be read.
  • A trait can't have statics; put them in the classes that use it.
  • There is no static var: a value that changes belongs in a var of the script, or a field of an object.

Records

A record is plain data: a list of fields, every one of which can be read, and none of which ever changes. It's for data that comes from, or goes to, the outside, like JSON:

records.hem
record Point
  x: Int
  y: Int = 0

  def plus(other: Point): Point
    return new Point(x: self.x + other.x, y: self.y + other.y)
  end
end

const a = new Point(x: 1, y: 2)

print(a.x)                     # prints 1
print(a.plus(new Point(x: 3))) # prints Point(x: 4, y: 2)

Fields are written name: Type, or name: Type = default, with no readable, const or var: they're always readable and never change. Records can have methods and statics, but no method can change one, and they can't use traits.

To get a different record, make a new one, or a changed copy with with: link.with(read: true) is link with read changed, and the rest the same. link itself doesn't change. Like objects, records are values, and equal when their fields are:

changed-copy-with.hem
record Counter
  count: Int
end

var counter = new Counter(count: 1)

counter.count = 2 # error: 'count' can't be changed: Counter is a record, and records never change; make a changed copy instead, like with(count: ...)

const next = counter.with(count: 2)

print(next.count)    # prints 2
print(counter.count) # prints 1

Class or record?

Use a class for something with behaviour and state of its own, and a record for data.

Class
Something that does things. It holds state, decides which fields outside code may read or change, and has methods that change it.
Record
Data, often on its way in or out of the program. Every field can be read, none ever changes, and with makes changed copies.