Search code examples
smalltalksqueak

Implementation of new with argument in smalltalk


I basically want to implement new which can accept argument e.x obj := SomeClass new: 'a'. I tried to implement this way

initialize: bdata
    data := bdata

But this doesn't work. seems like I am doing some silly mistake because of lack of knowledge. I try to google it but couldn't find any example. Please help.


Solution

  • In Smalltalk, new and new: are not keywords, but regular messages. They are simply implemented by the object's class. To write a method for an objects's class (rather than for an instance), click the "class" button in the system browser. There, you could implement your new: method.

    Note, however, that it is usually not a good idea to name your own instance creation method new:. Since this is a regular method, you can name it anything you want. For example, MyClass withBData: foo. Make it a nice descriptive name. It could look like

    withBData: bdata
        | inst |
        inst := self new.
        inst bdata: bdata.
        ^inst