<p>I've been reading a lot lately about the next release of Java possibly supporting <a href="http://en.wikipedia.org/wiki/Closure_%28computer_science%29" rel="noreferrer">closures</a>.  I feel like I have a pretty firm grasp on what closures are, but I can't think of a solid example of how they would make an Object-Oriented language "better".  Can anyone give me a specific use-case where a closure would be needed (or even preferred)?</p>

[{'answer_id': 50263, 'author': 'jodonnell', 'author_id': 4223, 'author_profile': 'https://Stackoverflow.com/users/4223', 'pm_score': 5, 'selected': False, 'text': "<p>The most obvious thing would be a pseudo-replacement for all those classes that just have a single method called run() or actionPerformed() or something like that.  So instead of creating a Thread with a Runnable embedded, you'd use a closure instead.  Not more powerful than what we've got now, but much more convenient and concise.</p>\n\n<p>So do we <em>need</em> closures?  No.  Would they be nice to have?  Sure, as long as they don't feel bolted on, as I fear they would be.</p>\n"}, {'answer_id': 50265, 'author': 'Gulzar Nazim', 'author_id': 4337, 'author_profile': 'https://Stackoverflow.com/users/4337', 'pm_score': 4, 'selected': False, 'text': '<p>I suppose for supporting core functional programming concepts, you need closures. Makes the code more elegant and composable with the support for <a href="http://martinfowler.com/bliki/Closure.html" rel="nofollow noreferrer">closures</a>. Also, I like the idea of passing around lines of code as parameters to functions.</p>\n'}, {'answer_id': 50267, 'author': 'jfs', 'author_id': 4279, 'author_profile': 'https://Stackoverflow.com/users/4279', 'pm_score': 1, 'selected': False, 'text': '<p><a href="http://www.blog.dannynet.net/archives/87" rel="nofollow noreferrer">Java Closure Examples</a></p>\n'}, {'answer_id': 50274, 'author': 'Shog9', 'author_id': 811, 'author_profile': 'https://Stackoverflow.com/users/811', 'pm_score': 5, 'selected': False, 'text': '<p>They don\'t make an Object-Oriented language better. They make practical languages more practical. </p>\n\n<p>If you\'re attacking a problem with the OO hammer - represent everything as interactions between objects - then a closure makes no sense. In a class-based OO language, closures are the smoke-filled back rooms where stuff gets done but no one talks about it afterwards. Conceptually, it is abhorrent. </p>\n\n<p>In practice, it\'s extremely convenient. I don\'t really want to define a new type of object to hold context, establish the "do stuff" method for it, instantiate it, and populate the context... i just want to tell the compiler, "look, see what i have access to right now? That\'s the context i want, and here\'s the code i want to use it for - hold on to this for me \'till i need it". </p>\n\n<p>Fantastic stuff. </p>\n'}, {'answer_id': 50277, 'author': 'Tom Hawtin - tackline', 'author_id': 4725, 'author_profile': 'https://Stackoverflow.com/users/4725', 'pm_score': 3, 'selected': False, 'text': '<p>Java has had closures since 1.1, just in a very cumbersome and limited way.</p>\n\n<p>They are often useful wherever you have a callback of some description. A common case is to abstract away control flow, leaving the interesting code to call an algoritm with a closure that has no external control flow.</p>\n\n<p>A trivial example is for-each (although Java 1.5 already has that). Whilst you can implement a forEach method in Java as it stands, it\'s far too verbose to be useful.</p>\n\n<p>An example which already makes sense with existing Java is implementing the "execute around" idiom, whereby resource acquisition and release is abstracted. For instance, file open and close can be done within try/finally, without the client code having to get the details right.</p>\n'}, {'answer_id': 50281, 'author': 'l0st3d', 'author_id': 5100, 'author_profile': 'https://Stackoverflow.com/users/5100', 'pm_score': 2, 'selected': False, 'text': '<p>As a java developer who is trying to teach themselves lisp in an attempt to become a better programmer, I would say that I would like to see the Josh Block proposal for closures implemented.  I find myself using anonymous inner classes to express things like what to do with each element of a list when aggregating some data.  To would be nice to represent that as a closure, instead of having to create an abstract class.</p>\n'}, {'answer_id': 54180, 'author': 'Pop Catalin', 'author_id': 4685, 'author_profile': 'https://Stackoverflow.com/users/4685', 'pm_score': 3, 'selected': False, 'text': "<p>Java doesn't need closures, an Object oriented language can do everything a closure does using intermediate objects to store state or do actions (in Java's case inner classes). \nBut closures are desirable as a feature because they greatly simplify the code and increase readability and as a consequence the maintainability of the code.</p>\n\n<p>I'm no Java specialist but I'm using  C# 3.5 and closures are one of my favorite features of the language, for example take the following statement as an example:</p>\n\n<pre><code>// Example #1 with closures\npublic IList&lt;Customer&gt; GetFilteredCustomerList(string filter) {\n    //Here a closure is created around the filter parameter\n    return Customers.Where( c =&gt; c.Name.Contains(filter)).ToList();\n}\n</code></pre>\n\n<p>now take an equivalent example that doesn't use closures</p>\n\n<pre><code>//Example #2 without closures, using just basic OO techniques\npublic IList&lt;Customer&gt; GetFilteredCustomerList(string filter) {\n    return new Customers.Where( new CustomerNameFiltrator(filter));\n}\n... \npublic class CustomerNameFiltrator : IFilter&lt;Customer&gt; {\n    private string _filter;\n    public  CustomerNameFiltrator(string filter) {\n         _filter = filter;\n    }\n    public bool Filter(Customer customer) {\n        return customer.Name.Contains( _filter);\n    }\n}\n</code></pre>\n\n<p>I know this is C# and not Java but the idea is the same, closures are useful for conciseness, and make code shorter and more readable. Behind the scenes, the closures of C# 3.5 do something that's looks very similar to example #2 meaning the compiler creates a private class behind the scenes and passes the 'filter' parameter to it.</p>\n\n<p>Java doesn't need closures to work, as a developer you don't need them either, but, they are useful and provide benefits so that means that they are desirable in a language that is a production language and one of it's goals is productivity.</p>\n"}, {'answer_id': 63879, 'author': 'jrudolph', 'author_id': 7647, 'author_profile': 'https://Stackoverflow.com/users/7647', 'pm_score': 4, 'selected': False, 'text': '<p>There are some very useful \'higher order functions\' which can do operations on lists using closures. Higher order functions are functions having \'function objects\' as parameters.</p>\n\n<p>E.g. it is a very common operation to apply some transformation to every element in a list. This higher order function is commonly called \'map\' or \'collect\'. (See the *. spread operator of <a href="http://groovy.codehaus.org/Operators" rel="noreferrer" title="Groovy Operators">Groovy</a>).</p>\n\n<p>For example to square each element in a list without closures you would probably write:</p>\n\n<pre><code>List&lt;Integer&gt; squareInts(List&lt;Integer&gt; is){\n   List&lt;Integer&gt; result = new ArrayList&lt;Integer&gt;(is.size());\n   for (Integer i:is)\n      result.add(i*i);\n   return result;\n}\n</code></pre>\n\n<p>Using closures and map and the proposed syntax, you could write it like that:</p>\n\n<pre><code>is.map({Integer i =&gt; i*i})\n</code></pre>\n\n<p>(There is a possible performance problem here regarding boxing of primitive types.)</p>\n\n<p>As explained by Pop Catalin there is another higher order function called \'select\' or \'filter\': It can be used to get all the elements in a list complying to some condition. For example:</p>\n\n<p>Instead of:</p>\n\n<pre><code>void onlyStringsWithMoreThan4Chars(List&lt;String&gt; strings){\n   List&lt;String&gt; result = new ArrayList&lt;String&gt;(str.size()); // should be enough\n   for (String str:strings)\n      if (str.length() &gt; 4) result.add(str);\n   return result;\n}\n</code></pre>\n\n<p>Instead you could write something like</p>\n\n<pre><code>strings.select({String str =&gt; str.length() &gt; 4});\n</code></pre>\n\n<p>using the proposal.</p>\n\n<p>You might look at the Groovy syntax, which is an extension of the Java language to support closures right now. See the chapter on collections of the <a href="http://groovy.codehaus.org/Collections" rel="noreferrer" title="Groovy User Guide">Groovy User Guide</a> for more examples what to do with closures.</p>\n\n<p>A remark:</p>\n\n<p>There is perhaps some clarification needed regarding the term \'closure\'. What I\'ve shown above are strictly spoken no closures. They are just \'function objects\'. \nA closure is everything which can capture - or \'close over\' - the (lexical) context of the code surrounding it. In that sense there are closures in Java right now, i.e. anonymous classes:</p>\n\n<pre><code>Runnable createStringPrintingRunnable(final String str){\n    return new Runnable(){\n       public void run(){\n          System.out.println(str); // this accesses a variable from an outer scope\n       }\n    };\n}\n</code></pre>\n'}, {'answer_id': 509851, 'author': 'benjismith', 'author_id': 22979, 'author_profile': 'https://Stackoverflow.com/users/22979', 'pm_score': 2, 'selected': False, 'text': '<p>When closures finally arrive in Java, I will gleefully get rid of all my custom comparator classes.</p>\n\n<pre><code>myArray.sort( (a, b) =&gt; a.myProperty().compareTo(b.myProperty() );\n</code></pre>\n\n<p>...looks a helluva lot better than...</p>\n\n<pre><code>myArray.sort(new Comparator&lt;MyClass&gt;() {\n   public int compare(MyClass a, MyClass b) {\n      return a.myProperty().compareTo(b.myProperty();\n   }\n});\n</code></pre>\n'}, {'answer_id': 716642, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>Not only that benjismith, but I love how you can just do...</p>\n\n<p>myArray.sort{ it.myProperty }</p>\n\n<p>You only need the more detailed comparator you've shown when the natural language comparison of the property doesn't suit your needs.</p>\n\n<p>I absolutely love this feature.</p>\n"}, {'answer_id': 716716, 'author': 'cygil', 'author_id': 42076, 'author_profile': 'https://Stackoverflow.com/users/42076', 'pm_score': 3, 'selected': False, 'text': '<blockquote>\n  <p>I\'ve been reading a lot lately about the next release of Java possibly supporting closures. I feel like I have a pretty firm grasp on what closures are, but I can\'t think of a solid example of how they would make an Object-Oriented language "better."</p>\n</blockquote>\n\n<p>Well, most people who use the term "closure" actually mean "function object", and in this sense, function objects make it possible to write simpler code in certain circumstances such as when you need custom comparators in a sort function.  </p>\n\n<p>For example, in Python:</p>\n\n<pre><code>def reversecmp(x, y):\n   return y - x\n\na = [4, 2, 5, 9, 11]\na.sort(cmp=reversecmp)\n</code></pre>\n\n<p>This sorts the list a in reverse order by passing the custom comparison functoin reversecmp.  The addition of the lambda operator makes things even more compact:</p>\n\n<pre><code>a = [4, 2, 5, 9, 11]\na.sort(cmp=lambda x, y : y - x)\n</code></pre>\n\n<p>Java does not have function objects, so it uses "functor classes" to simulate them.  In Java you do the equivalent operation by implementing a custom version of the Comparator class, and passing that to the sort function:</p>\n\n<pre><code>class ReverseComparator implements Comparator {\n   public compare(Object x, Object y) {\n      return (Integer) y - (Integer) x;\n   }\n\n...\n\nList&lt;Integer&gt; a = Arrays.asList(4, 2, 5, 9, 11);\nCollections.sort(a, new ReverseComparator());\n</code></pre>\n\n<p>As you can see, it gives the same effect as closures, but is clumsier and more verbose.  However, the addition of anonymous inner classes obviates most of the pain:</p>\n\n<pre><code>List&lt;Integer&gt; a = Arrays.asList(4, 2, 5, 9, 11);\nComparator reverse = new Comparator() {\n   public Compare(Object x, Object y) {\n       return (Integer) y - (Integer) x;\n   }\n}\nCollections.sort(a, reverse);\n</code></pre>\n\n<p>So I would say that the combination of functor classes + anonymous inner classes in Java is sufficient to compensate for the lack of true function objects, making their addition unnecessary.</p>\n'}, {'answer_id': 716763, 'author': 'Rainer Joswig', 'author_id': 69545, 'author_profile': 'https://Stackoverflow.com/users/69545', 'pm_score': 6, 'selected': False, 'text': "<p>As a Lisp programmer I would wish that the Java community understands the following difference: <strong>functions as objects vs. closures</strong>.</p>\n\n<p>a) <strong>functions can be named or anonymous</strong>. But they can also be objects of themselves. This allows functions to be passed around as arguments, returned from functions or stored in data structures. This means that functions are first class objects in a programming language.</p>\n\n<p>Anonymous functions don't add much to the language, they just allow you to write functions in a shorter way.</p>\n\n<p>b) <strong>A closure is a function plus a binding environment</strong>. Closures can be passed <em>downwards</em> (as parameters) or returned <em>upwards</em> (as return values). This allows the function to refer to variables of its environment, even if the surrounding code is no longer active.</p>\n\n<p>If you have <strong>a)</strong> in some language, then the question comes up what to do about <strong>b)</strong>? There are languages that have <strong>a)</strong>, but not <strong>b)</strong>. In the functional programming world <strong>a)</strong> (functions) and <strong>b</strong> (functions as closures) is nowadays the norm. Smalltalk had <strong>a)</strong> (<em>blocks</em> are anonymous functions) for a long time, but then some dialects of Smalltalk added support for <strong>b)</strong> (blocks as closures).</p>\n\n<p>You can imagine that you get a slightly different programming model, if you add functions and closures to the language. </p>\n\n<p>From a pragmatic view, the anonymous function adds some short notation, where you pass or invoke functions. That can be a good thing.</p>\n\n<p>The closure (function plus binding) allows you for example to create a function that has access to some variables (for example to a counter value). Now you can store that function in an object, access it and invoke it. The context for the function object is now not only the objects it has access to, but also the variables it has access to via bindings. This is also useful, but you can see that variable bindings vs. access to object variables now is an issue: when should be something a <em>lexical</em> variable (that can be accessed in a closure) and when should it be a variable of some object (a <em>slot</em>). When should something be a closure or an object? You can use both in the similar ways. A usual programming exercise for students learning Scheme (a Lisp dialect) is to write a simple object system using closures.</p>\n\n<p>The result is a more complicated programming language and a more complicated runtime model. Too complicated?</p>\n"}, {'answer_id': 716783, 'author': 'Daniel Earwicker', 'author_id': 27423, 'author_profile': 'https://Stackoverflow.com/users/27423', 'pm_score': 2, 'selected': False, 'text': '<p>Closures in an imperative language (examples: JavaScript, C#, the forthcoming C++ refresh) are not the same as anonymous inner classes. They need to be able to capture modifiable references to local variables. Java\'s inner classes can only capture local <code>final</code> variables.</p>\n\n<p>Almost any language feature can be criticised as non-essential:</p>\n\n<ul>\n<li><code>for</code>, <code>while</code>, <code>do</code> are all just syntactic sugar over <code>goto</code>/<code>if</code>.</li>\n<li>Inner classes are syntactic sugar over classes with a field pointing to the outer class.</li>\n<li>Generics are syntactic sugar over casts.</li>\n</ul>\n\n<p>Exactly the same "non-essential" argument should have blocked the inclusion of all the above features.</p>\n'}, {'answer_id': 716804, 'author': 'philsquared', 'author_id': 32136, 'author_profile': 'https://Stackoverflow.com/users/32136', 'pm_score': 2, 'selected': False, 'text': '<p>A few people have said, or implied, that closures are just syntactic sugar - doing what you could already do with anonymous inner classes and making it more convenient to pass parameters in.</p>\n\n<p>They <em>are</em> syntactic sugar in the same sense that Java is syntactic sugar for assembler (that "assembler" could be bytecode, for sake of argument). In other words they raise they level of abstraction, and this is an important concept.</p>\n\n<p>Closures promote the concept of the function-as-object to a first class entity - one that increases the expressiveness of code, rather than cluttering it with even more boilerplate.</p>\n\n<p>An example that\'s close to my heart has already been mentioned by Tom Hawtin - implementing the Execute Around idiom, which is just about the only way to get RAII into Java. <a href="http://www.levelofindirection.com/journal/2009/9/24/raii-and-closures-in-java.html" rel="nofollow noreferrer">I wrote a blog entry on exactly that subject</a> a couple of years ago when I first heard closures might be coming.</p>\n\n<p>Ironically, I think the very reason that closures would be good for Java (more expressiveness with less code) may be what rattles many Java advocates. Java has a mindset of "spell everything out the long way". That and the fact that closures are a nod towards a more functional way of doing things - which I also see as a Good Thing, but may water down the pure OO message that many in the Java community hold dear.</p>\n'}, {'answer_id': 2472965, 'author': 'Neal Ravindran', 'author_id': 296883, 'author_profile': 'https://Stackoverflow.com/users/296883', 'pm_score': 0, 'selected': False, 'text': "<p>What about readability and maintainability...one-liner closures are harder to understand and debug, imo\nSoftware has looong life and you can get people with rudimentary knowledge of the language to maintain it...So spread out logic better than one-liners for easy maintenance...You generally don't have a software star looking after software after its release...</p>\n"}, {'answer_id': 4665228, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': "<p>You might want to look at Groovy, a language that's mostly compatible with Java, and runs on the JRE, but supports Closures.</p>\n"}, {'answer_id': 6455738, 'author': 'Giorgio', 'author_id': 815409, 'author_profile': 'https://Stackoverflow.com/users/815409', 'pm_score': 2, 'selected': False, 'text': '<p>I have been thinking a lot about the topic of this <strong>very interesting question</strong> in\nthe last few days. First of all, if I have understood correctly, Java already has\nsome basic notion of closures (defined through anonymous classes) but the new feature\nthat is going to be introduced is the support for closures based on anonymous functions.</p>\n\n<p>This extension will definitely make the language more expressive but I am not sure\nif it really fits with the rest of the language.\nJava has been designed as an object-oriented language with no support for functional programming: Will the new semantics be easy to understand? Java 6 does not even have functions, will Java 7 have anonymous functions but no "normal" functions?</p>\n\n<p>My impression is that as new programming styles or paradigms like functional\nprogramming become more popular, everyone wants to use them in their\nfavourite OOP language. This is understandable: one wants to continue to use\na language they\'re familiar with while adopting new features. But in this way\na language can become really complex and lose coherence.</p>\n\n<p>So my attitude at the moment is to stick to Java 6 for OOP (I hope Java 6 will still\nbe supported for a while) and, in case I really get interested in doing OOP + FP,\nto take a look at some other language like Scala (Scala was defined to be multi-\nparadigm from the beginning and can be well integrated with Java) rather than switching\nto Java 7.</p>\n\n<p>I think Java owes its success to the fact that it combines a simple language with very\npowerful libraries and tools, and I do not think that new features like closures will\nmake it a better programming language.</p>\n'}, {'answer_id': 10572241, 'author': 'Edwin Dalorzo', 'author_id': 697630, 'author_profile': 'https://Stackoverflow.com/users/697630', 'pm_score': 2, 'selected': False, 'text': '<p>Now that <a href="http://jdk8.java.net/lambda/" rel="nofollow">JDK8</a> is about to be released there is more information available that can enrich the answers to this question.</p>\n\n<p>Bria Goetz, language architect at Oracle, has published a series of papers (yet drafts) on the current state of lambda expressions in Java. It does also cover closures as they are planning to release them in the upcoming JDK, which should be code complete <a href="http://openjdk.java.net/projects/jdk8/" rel="nofollow">around January 2013</a> and should be released around midyear 2013.</p>\n\n<ul>\n<li><a href="http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-4.html" rel="nofollow">The State of Lambda</a>: in the first page or two this article attempts to answer the question presented here. Although I still found it short in arguments, but is is full of examples.</li>\n<li><a href="http://cr.openjdk.java.net/~briangoetz/lambda/collections-overview.html" rel="nofollow">The State of Lambda - Libraries Edition</a>: this is also very interesting because it covers advantages like lazy evaluation and parallelism.</li>\n<li><a href="http://cr.openjdk.java.net/~briangoetz/lambda/lambda-translation.html" rel="nofollow">The Translation of Lambda Expressions</a>: which basically explains the desugaring process done by the Java compiler.</li>\n</ul>\n'}, {'answer_id': 15277773, 'author': 'Ustaman Sangat', 'author_id': 442716, 'author_profile': 'https://Stackoverflow.com/users/442716', 'pm_score': 0, 'selected': False, 'text': '<p>The lack of binding in anonymous function [i.e. if the variables (and method arguments if there is an enclosing method) of the outer context are declared <strong>final</strong> then they are available but not otherwise], I don\'t quite understand what that restriction actually buys.</p>\n\n<p>I use "final" profusely anyways. So, if my intent was to use the same objects inside the closure, I would indeed declare those objects final in the enclosing scope. But what would be wrong in letting the "closure [java a.i.c.]" just get a copy of the reference as if passed via a constructor (well that in fact is how it is done).</p>\n\n<p>If the closure wants to overwrite the reference, so be it; it will do so without changing the copy that the enclosing scope sees.</p>\n\n<p>If we argue that that would lead to unreadable code (e.g. maybe it\'s not straight-forward to see what the object reference is at the time of the constructor call for the a.i.c.), then how about at least making the syntax less verbose? Scala? Groovy?</p>\n'}]
['https://Stackoverflow.com/questions/50255', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1288/']