訊息傳送
在 Smalltalk 中,你所做的幾乎所有操作都是向物件傳送訊息 (在其他語言中稱為呼叫方法)。有三種型別的訊息:
一元資訊:
#(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."
二進位制訊息:
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"
關鍵字訊息:
'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."
語句中的多個訊息按優先順序進行評估
unary > binary > keyword
從左到右
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 )
如果要向同一物件傳送許多訊息,可以使用級聯運算子 ;
(分號):
OrderedCollection new
add: #abc;
add: #def;
add: #ghi;
yourself.
“這首先將訊息#new 傳送到 OrderedCollection 類(#new 只是一個訊息,而不是運算子)。它會產生一個新的 OrderedCollection。然後它將新的集合傳送三次訊息#add(帶有不同的引數),和你自己的資訊。“