smalltalk Smalltalk Syntax Message sending


Example

In Smalltalk almost everything you do is sending messages to objects (referred as calling methods in other languages). There are three types of messages:

Unary messages:

#(1 2 3) size
"This sends the #size message to the #(1 2 3) array.
 #size is a unary message, because it takes no arguments."

Binary messages:

1 + 2
"This sends the #+ message and 2 as an argument to the object 1.
 #+ is a binary message because it takes one argument (2)
 and it's composed of one or two symbol characters"

Keyword messages:

'Smalltalk’ allButFirst: 5.
"This sends #allButFirst: with argument 5 to the string 'Smalltalk',
 resulting in the new string 'talk'"

3 to: 10 by: 2.
"This one sends the single message #to:by:, which takes two parameters (10 and 2)
 to the number 3.
 The result is a collection with 3, 5, 7, and 9."

Multiple messages in a statement are evaluated by the order of precedence

unary > binary > keyword

and left to right.

1 + 2 * 3 " equals 9, because it evaluates left to right"
1 + (2 * 3) " but you can use parenthesis"

1 to:   #(a b c d) size   by:   5 - 4
 "is the same as:"
1 to: ( #(a b c d) size ) by: ( 5 - 4 )

If you want to send many messages to the same object, you can use the cascading operator ;(semicolon):

OrderedCollection new
  add: #abc;
  add: #def;
  add: #ghi;
  yourself.

"This first sends the message #new to the class OrderedCollection (#new is just a message, not an operator). It results in a new OrderedCollection. It then sends the new collection three times the message #add (with different arguments), and the message yourself."