Category:Smalltalk: Difference between revisions
Content added Content deleted
(→Other) |
|||
Line 496: | Line 496: | ||
[some code] fork "starts a new thread"</lang> |
[some code] fork "starts a new thread"</lang> |
||
=== Return from a Block === |
|||
it should be noted that a "ˆ" (return) inside a block will return from the enclosing method, NOT only from the block and that this is an essential semantic property of the return (technically, it may be a long return from a deeply nested call hierarchy, involving unwind actions). |
|||
This makes it possible to pass a block to eg. collections to enumerate elements up-to and until some condition is met. For example, if we need a helper method, which returns the first element from a dataset which meets some condition, we can write: |
|||
<lang smalltalk> |
|||
findSomeElementWhichMeetsCondition:conditionBlock thenDo:actionBlock ifNone:failBlock |
|||
dataSet do:[:eachElement | |
|||
(conditionBlock value:eachElement) ifTrue:[ |
|||
^ actionBlock value:eachElement |
|||
] |
|||
]. |
|||
^ failBlock value</lang> |
|||
Here, a block is passed to the dataSet's "do:" method, which will return (if invoked inside the "do:") from the containing findSomeElement method. |
|||
If a block-return (as eg. in JavaScript) would one return from itself, this wasn't possible, and ugly workarounds (like exceptions or long-jumps) were needed. |
|||
There are rare situations, where an explicit block return is needed (for example, to break out of a loop in the middle, without returning from the method). For this, block provides a special "valueWithExit" method, so you can write: |
|||
<lang smalltalk>1 to:10 do:[:outerLoopsI | |
|||
[:exit | |
|||
1 to:10 do:[:innerLoopsI | |
|||
... |
|||
someCondition ifTrue:exit |
|||
] |
|||
] valueWithExit |
|||
]</lang> |
|||
=== Exceptions and Handlers === |
=== Exceptions and Handlers === |