. .

st4u

ST 4U 183: Blocks in Smalltalk

January 20, 2012 12:35:03.517

Today's Smalltalk 4 You takes a look at Blocks in VA Smalltalk. If you have trouble viewing it here in the browser, you can also navigate directly to YouTube. To watch now, click on the image below:

Blocks.

If you have trouble viewing that directly, you can click here to download the video directly. If you need the video in a Windows Media format, then download that here.

You can also watch it on YouTube:


Today we'll look at block closures in VA Smalltalk. To get started, you should browse class Block, and take a look at the hierarchy. Typically, when you create a block, it will be an instance of the first subclass:

Blocks

Blocks represent a deferred bit of code - a loose method, if you will. They encapsulate pre-compiled behavior that can be passed around and executed later, by using #value (or one of the variants that take arguments). Below is the code we'll be using to explore blocks:


"Blocks"

block1 := [10 + 1].

block2 := [:input | input + 1].

block3 := [:a :b :c :d :e :f | a, b, c, d, e, f, ' - concatenated'].


val1 := block1 value. 11

val2 := block2 value: 1. 2

val3 := block3 valueWithArguments: #('one ' 'two ' 'three ' 'four' ' five' ' six').

val3 := block3 
		valueWithArguments: #('one ' 'two ' 'three ' 'four' ' five' ' six') 
		onReturnDo: [].
		
val3 := block3 
		valueWithArguments: #('one ' 'two ' 'three ' 'four' ' five' ' six') 
		onReturnDo: [:returnVal | Transcript show: 'Answer was: ', returnVal].
		

To create a block, simply encapsulate the desired code in square braces. As you can see above, using the [:arg1 :arg2 26 | ] notation, you can specify arguments to the block. To execute, you use:

  • #value - No arguments
  • #value: (up to three arguments with #value:value:value)
  • #valueWithArguments: (passing an array)

You can also specify an action block to execute when the block returns, and this block can (but does not have to) take one argument - the return result from the first block. Blocks, like methods, return the result of the last expression executed.

To see that last part in action, try executing the last statement above - you should see something like the following in the Transcript:

Blocks

Just try executing each line in the code above, inspecting or displaying the results - make sure you understand how each one of them works, then try a few examples of your own.

Need more help? There's a screencast for other topics like this which you may want to watch. Questions? Try the "Chat with James" Google gadget over in the sidebar.

Technorati Tags: , ,

Enclosures:
[st4u183-iPhone.m4v ( Size: 7305084 )]

posted by James Robertson

 Share Tweet This