Objects

This note is focused on the implementation of a class.

Object-oriented languages allow for the creation of objects which specify both data and behaviour.

class Counter {
    var value = 0

    def get() = value

    def incrementBy(amount: Int) = {
        value = value + amount
    }
}

val counter = new Counter

counter.incrementBy(42)
counter.incrementBy(-5)
counter.get() // 37

We can do the same thing with closures:

def newCounter: (() => Int, (Int) => Unit) = {
    var value = 0

    def get() = value

    def incrementBy(amount: Int) = {
        value = value + amount
    }

    (get, increment)
}

val counter2 = newCounter()

counter2._2(42) // Tuple access in Scala
counter2._2(-5)
counter2._1() // 37