Classes

Objects

Definition

An object is a structure containing state (data) and behaviour (procedures)

class Counter {
    var value = 0 // Data
    
    def get() = value // Procedures
    def incrementBy(amount: Int) = {
        value = value + amount
    }
}

val c = new Counter
val c2 = new Counter

c.incrementBy(42)
c2.incrementBy(100)
c.incrementBy(-5)
c.get()  // 37
c2.get() // 100


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

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

    (get, incrementBy)
}

val fc = newCounter
val fc2 = newCounter

// Access pair elements
fc._2(42)
fc2._2(100)
fc._2(-5)
fc._1()  // 37
fc2._1() // 100
Definition

An object is a collection of closures (indexed by names) that close over a common enviornment of data