Everyone says ‘Hi’

Smalltalk syntax is pretty weird, right? I mean, there’s no curly brackets anywhere, and there’s all those words, and no semi-colons, only colons! Colons!

Well, I’m not going to defend it. Finishing your statements with a full stop, or maybe an exclamation mark, is pretty weird, right?

Actually, I think that the Smalltalk syntax is pretty much the most literate syntax of any computer language. In fact, it’s one of the main things I love about Smalltalk. It isn’t quite like English, though, so a few pointers are in order.

"This is a comment"

'This is a string'

OK, Smalltalk code consists solely of sending messages to objects. What does that mean? Let’s start with Hello World.

'Hello World' displayNl!

OK, 'Hello World' is an object - a String, and displayNl is a message that is being sent to it. All objects respond to displayNl, by printing a representation of themselves to the transcript (usually standard output). The exclamation mark triggers evaluation in a script.

Let’s try doing the same thing the other way around:

Transcript << 'Hello World' ; nl!

This time, we’re sending messages to the transcript directly. Now, << is also a message. The first kind of message we saw, like displayNl doesn’t take any arguments, but messages that are compose of symbols take one; in this case, our 'Hello World' string. The Transcript responds to << by printing the argument, whatever it is, on itself.

The semi-colon, on the other hand, is not a message; it’s one of the reserved symbols, and it means ’send the next message to the same object as the last one’. What is the next message? It’s nl, which the transcript responds to by printing a newline.

There’s one more kind of message, which takes one or more arguments:

'Hello World' displayOn: Transcript!

Hopefully, you’ll be able to guess that displayOn: is a message being sent to ‘Hello World’, with the parameter Transcript. Keyword messages like this can have more than one argument. For every argument, there’s another keyword, like this:

'Hello World' copyFrom: 7 to: 11!

That’s one message, copyFrom:to:, with two arguments, 7 and 11.

You may as well know that the three kinds of messages are called unary, binary and keyword messages.

Before we finish this section, if you’re thinking that String’s displayOn: and the transcript’s << sound suspiciously like the same thing, that’s because they are. In order to print an object with <<, the Transcript sends:

anObject displayOn: self

This is an example of double dispatch where two objects co-operate to perform an action.

Back: How to make Smalltalk
Forward: Dead Against It