Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In Smalltalk, closures can hold a reference to an "outer context". The outer context is typically the the stack frame of the method that created the closure, but for nested closures, it might be another closure. </p> <p>Closures that hold a reference to an outer context are expensive, since (I guess) they prevent the corresponding stack to be garbage collected. Therefore, closures reference an outer context only when really needed:</p> <p><em>Clean closures</em>: closures with no reference to anything local. They do not need to reference the outer context. </p> <p>E.g. <code>[ Transcript show: 'something' ]</code></p> <p><em>Copying closures</em>: closures with reference to variable that don't change after the closure is created. The value of the variable at the time the closure is created is copied in the closure itself. Then, there is no need to keep a reference to the outer context. E.g. </p> <blockquote> <p>| list |<br> list := OrderedCollection new.<br> 1 to: 5 do: [ :i | list add: i ].</p> </blockquote> <p><em>Full closures</em>: closures that keep a reference to the outer context. E.g.</p> <blockquote> <p>| counter |<br> counter := 0.<br> 1 to: 5 do: [ :i | counter := counter + 1 ].</p> </blockquote> <p>Full closures are needed if the variable that is closed over is mutated after the closure is created, but also for <em>non-local returns</em>. Regarding non-local return, you might enjoy this <a href="http://gafter.blogspot.ch/2006/08/tennents-correspondence-principle-and.html" rel="nofollow">blog post from Neal Gafter</a>. </p> <p>A good read is also Brian Goetz' <a href="http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-4.html" rel="nofollow">State of the Lambda</a> on closures in upcoming JDK 7. Amongst others, I found interesting the discussion on why they will stick with Java limation to capture only <em>eventually final</em> variable and prohibit capture of mutable local variables. The example of full closure above will not be supported. The argument they claim is that it's mostly serial idiom. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload