Search code examples
runtimesqueakclass-method

Compiling a class method in squeak in run-time


I would like to add a class method during run time in squeak. I know that there is a method compile, which is defined in Behaviour class, but this one adds the new method I want to the class Instance methods. Is there a way to compile it to the class methods (so it will be a method which is defined for the class, and not for an instance of the class).

Thanks,


Solution

  • As every class is itself an object, a class itself has a class, too. This class is an instance of Metaclass, which inherits from Behavior. Thus, you can use #compile: on a class's class for class methods just like you would on a class for instance methods.

    A simple example:

    An instance method on Number:

    Number compile: 
    'succ
       ^ self + 1
    '
    

    A class method on Number class:

    Number class compile:
    'one
        ^ self zero + 1
    '