I'm reading a book using VisualWorks and I try to write the code in GNU Smalltalk. I have this:

OrderedCollection subclass: Stack [
    push: anObject [
         self addLast: anObject.
    ]

    pop [
        self isEmpty
           ifTrue: [^nil]
           ifFalse: [^self removeLast].
    ]
]

| st |
st := Stack new.
st push: 'a'.
Transcript show: st pop.

but it doesn't work. Can someone please explain me what am I doing wrong?

有帮助吗?

解决方案

I'm assuming you're getting Object: Stack error: should not be implemented in this class, use #basicNew instead?

If so, then it looks like you need to add <shape: inherit> in the body of your subclass.

See:

That seems like a bit of a leaky abstraction to me - but I guess it is what it is.

其他提示

The primary problem is a design one. When learning smalltalk and object orientation, you will be happier if you choose composition rather than inheritance by default. A stack has a very limited interface

push: anElement
pop
isEmpty

so why not make a class Stack with an instance variable stackData

Stack>>initialize
    stackData := OrderedCollection new

An OrderedCollection has a very wide interface, and this way you get a Stack that only responds to a very narrow interface. That makes it much easier to understand and use.

There is nothing wrong with your code. It's GNU-ST which does wierd things.

In other Smalltalks, this works like a charm. Here is what I typed into a Smalltalk/X workspace, and it does the expected (shows 'a' on the Transcript):

OrderedCollection 
    subclass: #MyStack
    instanceVariableNames:''
    classVariableNames:''
    poolDictionaries:''.

MyStack compile:'
    push: anObject
         self addLast: anObject.
'.

MyStack compile:'
    pop
        self isEmpty
           ifTrue: [^nil]
           ifFalse: [^self removeLast].
'.

| st |

st := XStack new.
st push: 'a'.
Transcript show: st pop.
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top