links to this page:    
View this PageEdit this PageUploads to this PageHistory of this PageTop of the SwikiRecent ChangesSearch the SwikiHelp Guide
How asString Works
Last updated at 12:33 pm UTC on 17 January 2006
Note: You can fetch this essay as a project.

This is an exploration of how the asString function works. By observing how the basic classes implement this function, and how it is used, we can write better classes. Fortunately with Squeak it is easy to explore this sort of thing.

First we want to look at implementations of the asString method. Just double click on the word asString then press Alt-m. Alt-m should bring up a window listing Implementors of asString. Let's take a look at the following:

String asString
Returns self. This is the simplest implementation.

Text asString
Text is composed of a string and markup information in a RunArray (don't believe it? Select Text and press Alt-b for browse. Text class has an informative class comment. Take a moment to read it!). To get Text as a string we just return the string part.

Character asString
Since a String is a collection of Characters, we simply create a new string with one character, self. String class also has a good class comment.
String>>with: doesn't exist. It is an inherited function. It is first implemented in Collection, then refined in ArrayedCollection.

Object asString
This provides a default implementation of asString for all classes. It returns self printString. So any class can implement printString and it will also support asString. Sorry but it doesn't work the other way around.
Object>>printString is interesting. The original version probably just returned a string representation of the object, but that can be dangerous. So it was refactored to call printStringLimitedTo: which allows you to limit how long the string is. That way you can avoid overflowing whatever you put the string into, and it works for most objects.
If you look at printStringLimitedTo: you see that it in turn calls printOn:. So for your own class you could just implement printOn: and Object adds support for printString and asString!
Implementors of printOn: do some interesting things. This will be the topic of another essay. For now you might want to check out the implementation in the Color class.

(hint: print the following:
Color blue
Color fromString: '#ffff00'
Color fromString: '#fe8080'