Last updated at 4:23 pm UTC on 6 April 2017
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 these two lines in a workspace and then execute them separately in succession.)
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.