Next: , Up: Some classes  


6.2.1 An array in Smalltalk

An array in Smalltalk is similar to an array in any other language, although the syntax may seem peculiar at first. To create an array with room for 20 elements, do24:

   x := Array new: 20

The Array new: 20 creates the array; the x := part connects the name x with the object. Until you assign something else to x, you can refer to this array by the name x. Changing elements of the array is not done using the := operator; this operator is used only to bind names to objects. In fact, you never modify data structures; instead, you send a message to the object, and it will modify itself.

For instance:

   x at: 1

which prints:

   nil

The slots of an array are initially set to “nothing” (which Smalltalk calls nil). Let’s set the first slot to the number 99:

   x at: 1 put: 99

and now make sure the 99 is actually there:

   x at: 1

which then prints out:

   99

These examples show how to manipulate an array. They also show the standard way in which messages are passed arguments ments. In most cases, if a message takes an argument, its name will end with ‘:’.25

So when we said x at: 1 we were sending a message to whatever object was currently bound to x with an argument of 1. For an array, this results in the first slot of the array being returned.

The second operation, x at: 1 put: 99 is a message with two arguments. It tells the array to place the second argument (99) in the slot specified by the first (1). Thus, when we re-examine the first slot, it does indeed now contain 99.

There is a shorthand for describing the messages you send to objects. You just run the message names together. So we would say that our array accepts both the at: and at:put: messages.

There is quite a bit of sanity checking built into an array. The request

   6 at: 1

fails with an error; 6 is an integer, and can’t be indexed. Further,

   x at: 21

fails with an error, because the array we created only has room for 20 objects.

Finally, note that the object stored in an array is just like any other object, so we can do things like:

   (x at: 1) + 1

which (assuming you’ve been typing in the examples) will print 100.


Footnotes

(24)

GNU Smalltalk supports completion in the same way as Bash or GDB. To enter the following line, you can for example type ‘x := Arr<TAB> new: 20’. This can come in handy when you have to type long names such as IdentityDictionary, which becomes ‘Ide<TAB>D<TAB>’. Everything starting with a capital letter or ending with a colon can be completed.

(25)

Alert readers will remember that the math examples of the previous chapter deviated from this.


Next: , Up: Some classes