Reputation: 371
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.
Upvotes: 3
Views: 364
Reputation: 61
You can use the basicNew method if you need to use your argument in the initialize method (as Uko mentions in his answer above).
withBData: bdata
^ (self basicNew bdata: bdata) initialize
Upvotes: 0
Reputation: 4623
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
Upvotes: 4
Reputation: 13386
Your code is too short to tell what is wrong. In general you should have an initialize with arg, something like this:
initialize: arg
self initialize.
instVar := arg
Then you can implement new:
like this:
new: arg
^ self basicNew
initialize: arg;
yourself
Note that new
is implemented as self basicNew initialize
, so if you are calling initialize
from your custom initialization method, you shouldn't use new
in your custom new, use basicNew
instead
Upvotes: 4