A class can travel without a suitcase

The word “class” tends to arrive with luggage. Hidden mutation. Objects whose contents can change while you are thinking about something else. A family photograph containing seventeen inheritance arrows.

Keep the first jar intact

Pooka’s ordinary classes do not have to carry all of that.

class Jar(contents: a) {
  map(change: fn(a) -> b) -> Jar(b) {
    Jar(change(contents))
  }
}

main() {
  let first = Jar(12)
  let second = first.map(fn(n) { n > 10 })
  assert first.contents == 12
  assert second.contents == True
}

Follow the new type

first:   Jar(Int)
change:  fn(Int) -> Bool
second:  Jar(Bool)

first.contents is still 12

The method creates a new jar. The first one remains a jar of integers. The second holds a Boolean. Nothing has reached backwards and replaced the original contents while its owner was looking away.

This gives the type checker an interesting obligation. The method’s return type is Jar(b), and b comes from the supplied function. Treating every jar as the receiver’s original Jar(a) would discard a real change in the program’s type information.

Use the returned value

Immutability also affects how an API should feel. A method that returns an updated value needs to make that result easy to use. Calling it and ignoring the return value cannot be mistaken for changing the receiver.

Inheritance introduces further questions about construction, field access and dispatch. Those deserve careful rules of their own. The existence of a pleasant little Jar is not evidence that every subclass problem has quietly solved itself.

What I like here is the combination: values that stay put, with methods near the operations they describe. Passing a class value between functions does not require giving every recipient authority to rewrite it.

Actors are where Pooka puts a different kind of work: changing state behind a process boundary.

The jar can travel as a value. It has no secret room that everybody else is rearranging.

— Peregrine Finch

· pooka, classes, types