Smalltalk Array Types

arrays, smalltalk, squeak

Solution

Here's a little walkthrough:

Firstly, we can find out the types resp. classes of the resulting objects:

- `#[] class` results in `ByteArray`

- `#() class` results in `Array`

- `{} class` also results in `Array`

So apparently the latter two produce Arrays while the first produces a ByteArray. ByteArrays are what you would expect -- fixed sized arrays of bytes.

Now we'll have to figure out the difference between `#()` and `{}`. Try evaluating `#(a b c)`, it results in `#(#a #b #c)`; however when you try to evaluate `{a b c}`, it doesn't work (because `a` is not defined). The working version would be `{#a. #b. #c}`, which also results in `#(#a #b #c)`.

The difference between `#()` and `{}` is, that the first takes a list of Symbol names separated by spaces. You're also allowed to omit the `#` signs. Using this notation you can only create Arrays that contain Symbols. The second version is the generic Array literal. It takes any expressions, separated by `.` (dots). You can even write things like `{1+2. anyObject complexOperation}`.

This could lead you to always using the `{}` notation. However, there are some things to keep in mind: The moment of object creation differs: While `#()` Arrays are created during compilation, `{}` Arrays are created during execution. Thus when you run code with an `#()` expression, it will also return the same Array, while `{}` only returns equal Arrays (as long as you are using equal contents). Also, AFAIK the `{}` is not necessarily portable because it's not part of the ST-80 standard.

Problem

When looking at Smalltalk syntax definitions I noticed a few different notations for arrays: ``` #[] "ByteArray" #() "Literal Array" {} "Array" ``` - Why are there different array types? In other programming languages I know there's only one kind of array independent of the stored type. - When to choose which kind? - Why do literal array and array have a different notation but same class?

Original source