Trouble with printOn: and super

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Trouble with printOn: and super

Fernando Rodríguez
Hi,

I have a class called Person (direct subclass of Object) that has a
'name' instance variable.

I tried to define a printOn: method like this:

printOn: aStream
        aStream
                nextPutAll: (name ifNil: [super printOn: aStream]
                                  ifNotNil: [:x| x]).

If the name variable is binded to something else nil, I want to print
it, otherwise I want to print some default stuff(whatever super
prints).

Whenever I run it before asigning something to name (when it's binded
to nil) I get a Does not understand error: 'Person does not understand
appendToStream:'.

The culprit seems to be the ifNil block. What am I doing
wrong? O:-)
Thanks


Reply | Threaded
Open this post in threaded view
|

Re: Trouble with printOn: and super

Christopher J. Demers
"Fernando" <[hidden email]> wrote in message
news:[hidden email]...
...

> I tried to define a printOn: method like this:
>
> printOn: aStream
> aStream
> nextPutAll: (name ifNil: [super printOn: aStream]
>           ifNotNil: [:x| x]).
> Whenever I run it before asigning something to name (when it's binded
> to nil) I get a Does not understand error: 'Person does not understand
> appendToStream:'.
>
> The culprit seems to be the ifNil block. What am I doing
> wrong? O:-)

Try putting a return before super printOn: aStream ex:
======
 printOn: aStream
 aStream
     nextPutAll: (name ifNil: [^super printOn: aStream]
           ifNotNil: [:x| x]).
======

What is happening is that super printOn: is returning self, which is then
being treated like a string and erroring.

Chris