消息发送
在 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(带有不同的参数),和你自己的信息。“