Next: Asynchronous message passing, Previous: Methods aren't essential but they are useful, Up: Tutorial [Contents]
Objects can also contain and define other object references, including in their outer constructor procedure.
Here is the definition of a “counting greeter” we call
^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 we can see near the top, times-called
is instantiated as an
^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