4.3: Message Sends
- Page ID
- 39586
There are three kinds of messages in Pharo. This distinction has been made to reduce the number of mandatory parentheses.
- Unary messages take no argument.
1 factorial
sends the messagefactorial
to the object 1. - Binary messages take exactly one argument.
1 + 2
sends the message + with argument 2 to the object 1. - Keyword messages take an arbitrary number of arguments.
2 raisedTo: 6 modulo: 10
sends the message consisting of the message selectorraisedTo:modulo:
and the arguments 6 and 10 to the object 2.
Unary messages. Unary message selectors consist of alphanumeric characters, and start with a lower case letter.
Binary messages. Binary message selectors consist of one or more characters from the following set:
+ - / \ * ~ < > = @ % | & ? ,
Keyword message selectors. Keyword message selectors consist of a series of alphanumeric keywords, where each keyword starts with a lower-case letter and ends with a colon.
Message precedence. Unary messages have the highest precedence, then binary messages, and finally keyword messages, so:
2 raisedTo: 1 + 3 factorial >>> 128
First we send factorial
to 3, then we send + 6
to 1, and finally we send raisedTo: 7
to 2. Recall that we use the notation expression >>>
to show the result of evaluating an expression.
Precedence aside, execution is strictly from left to right, so:
1 + 2 * 3 >>> 9
return 9 and not 7. Parentheses must be used to alter the order of evaluation:
1 + (2 * 3) >>> 7
Periods and semi-colons. Message sends may be composed with periods and semi-colons. A period separated sequence of expressions causes each expression in the series to be evaluated as a statement, one after the other.
Transcript cr. Transcript show: 'hello world'. Transcript cr
This will send cr
to the Transcript
object, then send it show: 'hello world'
, and finally send it another cr
.
When a series of messages is being sent to the same receiver, then this can be expressed more succinctly as a cascade. The receiver is specified just once, and the sequence of messages is separated by semi-colons:
Transcript cr; show: 'hello world'; cr
This has precisely the same effect as the previous example.