Search code examples
pharo

How do I override the printing of arrays?


printOn: aStream
    | normalized |
    normalized := self normalized.
    aStream nextPut: ${.
    self isEmpty ifFalse: [ 
        normalized printElem: 1 on: aStream.
        2 to: self size do: [ :i | 
            aStream nextPutAll: ' . '.
            normalized printElem: i on: aStream 
            ].
        ].
    aStream nextPut: $}

This printOn: method works, but the Inspector is using some other route to print the array. How do I to tell the Inspector to use the above method for my class that inherits from Array?


Solution

  • Inspector uses gtDisplayOn: to represent objects.

    In Object it is implemented as:

    gtDisplayOn: stream
        "This offers a means to customize how the object is shown in the inspector"
        ^ self printOn: stream
    

    However, Collection overrides it as:

    gtDisplayOn: stream
        self printNameOn: stream.
        stream
            space;
            nextPut: $[;
            print: self size;
            nextPutAll: (' item' asPluralBasedOn: self size);
            nextPut: $];
            space.
        self size <= self gtCollectionSizeThreshold 
            ifTrue: [ self printElementsOn: stream ]
    

    Just override it again in your class to use printOn: as Object does.