Reputation: 1079
I have the following code to create a collection as a member of a class:
CustomClass new members:Set new; yourself.
next I ask for the size
custom members size.
which results in obviously 0, but when I insert a custom element in the set and I ask for the size it results in an error telling me my custom elements are not indexable.
custom members add: MyCustomElement new.
custom members size. -> error
Why is this? How does one solve this issue in Smalltalk? Thanks in advance
Upvotes: 1
Views: 581
Reputation: 9512
The code you exhibit should not trigger the error.
But it's possible that you were bitten by the #add: message.
The #add: message returns the added element, this way you can chain additions like:
collection2 add: (collection1 add: element).
This also work with #at:put:
collection2 at: j put: (collection1 at: i put: k).
is much like
c2[ j ] = c1[ i ] = k;
Though, if you write something like:
| s e |
e := MyCustomElement new.
s := (Set new) add: e.
^s size
then the variable s will point to the same object than e, an instance of MyCustomElement, and not to the freshly created Set.
Above example thus send the message #size to an instance of MyCustomElement, and this sound very much like the error you described: this may trigger an error because the instances of this class are not indexable.
You can alternatively write:
(s := Set new) add: e.
or use a cascade that ends by sending #yourself to the Set, effectively returning the set itself:
s := (Set new) add: e; yourself.
Upvotes: 1