Edit Rename Upload Download Back to Top

Smalltalk Block Notation for Java Programmers

The logical relationship between method and block notation is not always made clear in Smalltalk books and training courses. So here it is.

In Smalltalk, block code is enclosed between square brackets (that's where the slang expression 'square-brackets language' for Smalltalk comes from, as opposed to the term 'curly-brackets language' for Java, C++ and C, and 'round-brackets language' for Lisp and Prolog). For example, Java's

   if (aBoolean) {some_code}

is written

   aBoolean ifTrue: [someCode]

in Smalltalk. However a Smalltalk block is much more than a block of code in other languages. A block (full name BlockClosure; if you're browsing a Smalltalk image, look for the class of that name) is a lightweight method. It's the method with no name. :-) To recast a method as block:

Thus
   myMethod
	someCode

corresponds to

   [someCode]

We evaluate a method by calling it.

   aMyClass myMethod.

We evaluate a block by sending it a 'value' message, either immediately

   [someCode] value.

or later

   myBlock := [someCode].
   ...
   myBlock value.

A method may have keywords, e.g

   MyClass>>showOnTranscript: aParameter and: anotherParameter
	Transcript show: aParameter; space; anotherParameter

So can a block. A block's parameters are separated from its body by an upright, and losing the method's name leaves the colons behind, like the grin of a cheshire cat.

   [: aParameter : anotherParameter | Transcript show: aParameter; space; anotherParameter]

It is conventional to remove the space between the colons and their parameters, so the above block would usually be written

   [:aParameter :anotherParameter | Transcript show: aParameter; space; anotherParameter]

The equivalent of a parametrised method call, such as

   aMyClass showOnTranscript: 5 and: 'pounds'.

is to send the block a message of the form

For example,
   [:aParameter :anotherParameter | Transcript show: aParameter; space; anotherParameter]
      value: 5 value: 'pounds'.

or

   myTwoArgBlock := [:aParameter :anotherParameter | Transcript show: aParameter; space; anotherParameter].
   ...
   myTwoArgBlock value: 5 value: 'pounds'.

Just as methods may declare temporary variables

   myMethod
	| myTemporaryVariable |
	myMethodCode

so may blocks

   [| myTemporaryVariable | myMethodCode]

and this combines with parameters in the obvious way

   [:aParameter :anotherParameter || myTemporaryVariable | myMethodCodeUsingParameters]

Summing up about Smalltalk's block construct:

Otherwise it reads just like a method.

(Back to new code syntax.)


Edit Rename Upload Download Back to Top