Next: , Previous: , Up: Tutorial   [Contents][Index]


4.4 Objects which contain objects

Objects can also contain and define other object references, including in their outer constructor procedure.

Here is the definition of a “counting greeter” called ^cgreeter:

(define (^cgreeter _bcom our-name)
  (define times-called
    (spawn ^mcell 0))
  (methods
   ((get-times-called)
    ($ times-called 'get))
   ((greet your-name)
    ;; increase the number of times called
    ($ times-called 'set
       (+ 1 ($ times-called 'get)))
    (format #f "[~a] Hello ~a, my name is ~a!"
            ($ times-called 'get)
            your-name our-name))))

As you can see near the top, times-called is instantiated as a ^cell like the one we defined earlier. The current value of this cell is returned by get-times-called and is updated every time the greet method is called:

goblins[1]> (define julius
              (spawn ^cgreeter "Julius"))
goblins[1]> ($ julius 'get-times-called)
; => 0
goblins[1]> ($ julius 'greet "Gaius")
; => "[1] Hello Gaius, my name is Julius!"
goblins[1]> ($ julius 'greet "Brutus")
; => "[2] Hello Brutus, my name is Julius!"
goblins[1]> ($ julius 'get-times-called)
; => 2