Smalltalk Blocks
The expression of the square bracket
Block Syntax
In the Smalltalk programming language, blocks are anonymous deferred pieces of code that can be stored in variables or passed as parameters. These are referred to as closures or lambdas. Literal blocks start and end with square brackets — []. In Pharo Smalltalk, a block is an instance of the BlockClosure class. In a block, the pipe character separates the parameters on the left and the expression on the right (e.g. [ :parameter | expression ]. A zero argument block will have no pipe (e.g. [ true ]). Parameters have alphanumeric names, and start with the colon character. The code in a block can be evaluated by calling the method value. The return value will be the result of evaluating the last expression in the block. A block with parameters can be executed by calling the equivalent value methods with parameters. (e.g. [:a | a] value: 1). If a block has more than four parameters, then you can evaluate the block with the valueWithArguments: array method. A literal array in Smalltalk has the syntax #(1 2 3 4 5).
Get Donald Raab’s stories in your inbox
Join Medium for free to get updates from this writer.
The following are some block examples that are evaluated with the specified parameters.
[ 0 ] value. // 0
[ :a | a ] value: 1. // 1
[ :a :b | a + b ] value: 1 value: 2. // 3
[ :a :b :c | a + b + c ] value: 1 value: 2 value: 3. // 6
[ :a :b :c :d | a + b + c + d] value: 1 value: 2 value: 3 value: 4. // 10
[ :a :b :c :d :e | a + b + c + d + e] valueWithArguments: #(1 2 3 4 5). // 15The classes of various blocks.
[ ] class. // ConstantBlockClosure
[ 0 ] class. // ConstanceBlockClosure
[ :a :b | a + b ] class. // FullBlockClosureBlocks in Practice
Blocks in Smalltalk are used to build control structures, including if-statements, for-loops, and internal iterators on collections.
If-statement
true ifTrue: [ 1 ]. // 1
false ifTrue: [ 1 ]. // nil
false ifFalse: [ 2 ]. // 2.
true ifTrue: [ 1 ] ifFalse: [2]. // 1
false ifTrue: [ 1 ] ifFalse: [2]. // 2For-loop
1 to: 10 do: [ :each | Transcript show: each ] // 12345678910Internal iterator
#(1 2 3 4 5) do: [:each | Transcript show: each ] // 12345
(1 to: 5) inject: 0 into: [ :a :b | a + b ]. // 15
(1 to: 10) select: [ :each | each even ]. // #(2 4 6 8 10)
(1 to: 10) select: [ :each | each odd ]. // #(1 3 5 7 9)Final Thoughts
Blocks are literally the building blocks of so many things in Smalltalk. I hope you found this brief introduction of blocks in Smalltalk interesting.
Thanks for reading!
I am the creator of and committer for the Eclipse Collections OSS project, which is managed at the Eclipse Foundation. Eclipse Collections is open for contributions. I am the author of the book, Eclipse Collections Categorically: Level up your programming game.







