Last updated at 9:57 am UTC on 24 February 2018
Code blocks in Smalltalk are self-contained pieces of computation which can be activated by sending them the #value message or one of its variants.
A Smalltalk block is Smalltalk’s term for a closure.
Enter the two lines below in a workspace.
Then put the curser into the first line and execute it. Then the code in the second line separately.
aBlock := [ Transcript open; show: 'Hello World'. ]
The entity delimited by the square brackets [...] is the block. In the first line it is assigned to the variable called aBlock, but not executed. In the second line it is executed by sending it (or rather the variable representing it) the #value message.
Blocks are a powerful way of parameterizing behavior (akin to procedure pointers in some other languages) and for example form the basis of some of Smalltalk's looping capabilities by providing message protocol like #whileTrue:, #whileFalse: in Boolean etc.
A block may be defined with arguments so that values may be passed into the block at execution time. The arguments are defined by variables defined to the left of a vertical bar ("|") separating the variables from the block expressions, The variable names are preceded by a colon (":") where they are defined but the colon is not used where they are used.
aBlock := [ :msg | Transcript open; show: msg ].
aBlock value: 'Hello World'.
Blocks are instances of class BlockContext.
"Simple scripts" (e.g. block as the target)