Change the way an Object is printed
Jump to navigation
Jump to search
Problem. Suppose you defined a Class, say User, and suppose this class contains the instance variables name
, id
, password
. When you create a new User object, it will print itself as aUser
. This might be ok, but suppose it is usefull for you to always see id
. What to do?
Solution. In the User object define the method printOn:
. Watch how it is defined on the class Object
and change it a bit, for example as:
printOn: aStream
|str|
str := ((self class name withArticle) , '-', self id asString).
aStream nextPutAll: str.
Cy. Defect: The method above is a bit Pythonic. This method definition is more Smalltalkish:
printOn: aStream
aStream nextPutAll: self class name;
nextPut: $-;
nextPutAll: self id asString .
Voila, now if you print a user you will see something like aUser-2132
. This very practical when you are listing several user objects, for the example in the inspector.
NM 10-Aug-2021. Tested Cuis5.0-4738.image