[plt-scheme] Accessing class in method?

From: Carl Eastlund (cce at ccs.neu.edu)
Date: Tue Oct 7 19:23:02 EDT 2008

Off the top of my head there are two ways to go about this, neither perfect.

One is the OO method: have B override A.  Any subclass of A will have
to do this.  The drawback: lots of duplicated code, and it goes wrong
if you forget to override somewhere.

The other is reflection: use object-info in the make method to extract
the class of the current object.  The drawback: not only is
object-info not guaranteed to be able to access the class of the
current object, but you have no guarantee your subclasses don't
introduce constructor arguments you don't know about.

This isn't an easy problem, much as it seems like it should be;
because subclasses have so much power to change their behavior,
automatically generating factory methods for them is nontrivial.
Choosing the best way to solve this will depend a lot on what you're
trying to do with your factory method and the structure of your
classes.  If you have more specific information, post it and maybe
someone can help you narrow down a better solution.

Good luck!


On Tue, Oct 7, 2008 at 7:06 PM, Sam Phillips <samdphillips at gmail.com> wrote:
> Ok, I'm not sure how clearly I can word this... I'm trying to write a
> method that creates an instance of the class that it is a method on, and
> I'm not sure how to go about it.  Here's an example:
>> (define a%
>    (class object%
>      (super-new)
>      (define/public (make)
>        (make-object a%))))
>> (make-object a%)
> #(struct:object:a% ...)
>> (send (make-object a%) make)
> #(struct:object:a% ...)
> So far so good.
>> (define b%
>    (class a% (super-new)))
>> (make-object b%)
> #(struct:object:b% ...)
>> (send (make-object b%) make)
> #(struct:object:a% ...)
> What I want is a way for calling "make" on b% to return an instance of
> b% not of a%.
> Cheers,
> Sam

Posted on the users mailing list.