Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 38 ยท Collections and Blocks

Blocks and Closures in Smalltalk: value, Parameters, Non-local Return

Master Smalltalk blocks: anonymous code you can store and run later with value, parameters, captured variables, non-local return, ensure: and ifCurtailed:, and how blocks power every control structure.

A block is a piece of code wrapped in square brackets that you can store in a variable, pass to a method and run later. It is Smalltalk's lambda, closure and callback in one. Blocks are everywhere: every conditional, loop, collection iteration, exception handler and sort order you will write is built from them, so this lesson is the key to the rest of the course.

Smalltalk code is read-only on this site. JavaScript stand-ins run in your browser.

Creating and evaluating a block

SMALLTALK
| greet |
greet := [ 'Hello, world' ].
greet value.          "-> 'Hello, world'"

Square brackets create the block; nothing inside runs until you send value. A block with parameters lists them first, each with a colon, followed by |:

SMALLTALK
| square add |
square := [ :x | x * x ].
square value: 7.                  "-> 49"
add := [ :a :b | a + b ].
add value: 3 value: 4.            "-> 7"

The messages are value, value:, value:value:, value:value:value: and value:value:value:value:. For more arguments use valueWithArguments: #(1 2 3 4 5). Passing the wrong number raises an error: numArgs tells you how many a block expects (add numArgs is 2).

The value of a block is the value of its last expression; an empty block [] answers nil.

SMALLTALK
[ 1. 2. 3 ] value.      "-> 3"
[ :x | | tmp | tmp := x + 1. tmp * 2 ] value: 4.    "-> 10"

Temporaries are declared after the parameters (| tmp |), and they are fresh for every evaluation.

Blocks are closures

A block remembers the variables visible where it was written, even if the surrounding method has finished:

SMALLTALK
adderFor: n
    ^ [ :x | x + n ]

| add10 |
add10 := self adderFor: 10.
add10 value: 5.         "-> 15"

n is captured. Blocks can also change captured variables:

SMALLTALK
| total |
total := 0.
#(1 2 3) do: [ :each | total := total + each ].
total.       "-> 6"

Two blocks that capture the same variable share it, which is how counters and accumulators work.

flowchart LR
    M["method adderFor: 10"] --> B["block [ :x | x + n ]"]
    M --> N["n = 10"]
    B -.captures.-> N
    B --> R["returned to the caller"]
    R -->|"value: 5"| V["15"]

The block keeps n alive after adderFor: has returned.

Blocks as arguments

Because blocks are objects, you pass them like any other value. Here is a method that takes a block:

SMALLTALK
Object >> repeat: n do: aBlock
    1 to: n do: [ :i | aBlock value: i ]

self repeat: 3 do: [ :i | Transcript show: i printString; cr ].

This is how every iteration method works. do:, collect:, select:, detect:ifNone:, sort: and ifTrue: are ordinary methods that take blocks.

Non-local return

A ^ inside a block returns from the method in which the block was written, not just from the block:

SMALLTALK
findFirstEven: numbers
    numbers do: [ :each |
        each even ifTrue: [ ^ each ] ].    "returns from findFirstEven:"
    ^ nil

When each even holds, ^ each ends the whole method, including the loop in do:. This is a feature: it gives you "break" and "return" without extra keywords. A block with ^ that outlives its method (stored and run later) raises BlockCannotReturn, because the method has already returned.

Cleanup: ensure: and ifCurtailed:

SMALLTALK
| file |
file := FileSystem workingDirectory / 'data.txt'.
[ file readStream upToEnd ] ensure: [ Transcript show: 'done'; cr ].

ensure: runs its argument block when the receiver block finishes, even if an error or a non-local return occurs, like finally. ifCurtailed: runs its argument only when the receiver block exits abnormally. Use ensure: to close files and release resources.

Exceptions use blocks too

SMALLTALK
[ 10 / 0 ]
    on: ZeroDivide
    do: [ :error | Transcript show: 'Cannot divide'; cr. 0 ].    "-> 0"

on:do: runs the receiver block and, if it raises the named exception, evaluates the handler block with the exception as its argument. More in the testing chapter.

Practical patterns

Callbacks: store a block in an instance variable and run it when something happens (button action: [ self save ]).

Lazy values: [ expensiveComputation ] is not computed until value. Pharo's lazy and ifNil: idioms rely on this.

Strategy: pass the varying part of an algorithm as a block (sortBlock), instead of subclassing.

Timing: [ 1000000 factorial ] timeToRun answers how long it took.

Dictionary default: dict at: key ifAbsent: [ 0 ], dict at: key ifAbsentPut: [ OrderedCollection new ].

Block syntax pitfalls

  • A block only runs when sent value...; forgetting it just returns the block object.
  • Parameters are read-only, like method arguments.
  • The number of arguments passed must match numArgs, otherwise wrongArgumentCount appears.
  • whileTrue: is sent to the condition block, so the condition must be a block, not a value: [ x < 10 ] whileTrue: [...].
  • Pharo's [ :x | ... ] cull: x passes arguments only if the block wants them, useful for callbacks.
JS Stand-in: blocks as closures

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Stand-in: non-local return and ensure:

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does [ :x | x * 2 ] value: 4 answer?

    value: passes 4 to the parameter x; the block answers its last expression, 8.
  2. 2. What does ^ do inside a block written in a method?

    A caret in a block returns from the method that contains the block.
  3. 3. Which message runs a cleanup block even when an exception or return exits the receiver block?

    ensure: always runs; ifCurtailed: runs only on abnormal exit.
  4. 4. Why does 3 > 2 whileTrue: [ ... ] not work as a loop?

    The condition has to be re-evaluated, so it is a block: [ x < 10 ] whileTrue: [ ... ].

Summary

  • A block is an object holding code; it runs only when sent value, value:, value:value:, and so on.
  • Blocks capture the variables around them and keep them alive (closures); blocks sharing a variable share its state.
  • ^ inside a block returns from the enclosing method; ensure: and ifCurtailed: handle cleanup.
  • Conditionals, loops, iteration, sorting and exception handling are all built from blocks passed as arguments.
  • Check numArgs, and remember that whileTrue: needs a block as its condition.

Next: Arrays and Ordered Collections