[racket] Overriding methods in Racket classes

From: Asumu Takikawa (asumu at ccs.neu.edu)
Date: Thu Jan 3 17:20:17 EST 2013

On 2013-01-03 17:01:54 -0500, Harry Spier wrote:
> In Racket is it possible to override a non-public method?
>
> [...]
>
> Apologies if I've missed something obvious but I've just started going
> through the Classes and Objects documentation.  I can see where you
> can declare a method public and overridable, or public and not
> overridable, but I don't see a declaration for a method to be private
> to the outside world but public and overridable to its sub-classes.

You can use local member names to accomplish this. It effectively makes
certain method names lexically scoped. Here is an example:

  #lang racket

  (define-values (bomb% detonator%)
    (let ()
      ;; lexically scoped method name
      (define-local-member-name detonate)
      (values
       (class object%
         (super-new)
         ;; public only while the name is in scope
         (define/public (detonate)
           (displayln "boom!")))
       (class object%
         (super-new)
         (init-field bomb)
         (define/public (trigger)
           (send bomb detonate))))))

  ;; error since `detonate` not in scope
  ;(send (new bomb%) detonate)

  ;; works
  (send (new detonator% [bomb (new bomb%)]) trigger)

Using local member names, the "outside world" is wherever the name is
not bound. If it is in scope, you can invoke it, override it, etc and
your method declarations are done normally.

Cheers,
Asumu

Posted on the users mailing list.