Is Groovy syntax an exact superset of Java syntax? - java

Being a Java programmer, I don't really have a Groovy background, but I use Groovy a lot lately to extend Maven (using GMaven). So far, I could use all the Java code I need in Groovy with the added Groovy sugar (metaclass methods, more operators, closures). My knowledge of Groovy is far from complete, but I like it, especially for Scripting purposes (I'm a bit careful about using a non-static typed language in an enterprise scenario, but that's not the topic here).
Anyway, the question is:
Is every bit of valid Java code automatically valid Groovy code? (I am talking about Source code, not compiled classes, I know Groovy can interact with Java classes.) Or are there Java constructs that are illegal in Groovy? Perhaps a reserved Groovy keyword that could be used as an identifier in Java, or something else? Or has Groovy deliberately been designed to be 100%-source compatible with Java?

Nope. The following are keywords in groovy, but not Java:
any as def in with
Additionally, while not keywords, delegate and owner have special meaning in closures and can trip you up if you're not careful.
Additionally, there are some minor differences in the language syntax. For one thing, Java is more flexible about where array braces occur in declarations:
public static void main(String args[]) // valid java, error in groovy
Groovy is parsed differently, too. Here's an example:
public class Test {
public static void main(String[] args) {
int i = 0;
i = 5
+1;
System.out.println(i);
}
}
Java will print 6, groovy will print 5.
While groovy is mostly source compatible with java, there are lots of corner cases that aren't the same. That said, it is very compatible with the code people actually write.

It isn't.
My favorite incompatibility: literal arrays:
String[] s = new String[] {"a", "b", "c"};
In Groovy, curly braces in this context would be expected to contain a closure, not a literal array.

There's a page on the Groovy site which documents some of the differences, and another page which lists gotchas (such as the newline thing)
There are other things as well, one example being that Groovy doesn't support the do...while looping construct

Others have already given examples of Java syntax that is illegal in Groovy (e.g. literal arrays). It is also worth remembering that some syntax which is legal in both, does not mean the same thing in both languages. For example in Java:
foo == bar
tests for identity, i.e. do foo and bar both refer to the same object? In Groovy, this tests for object equality, i.e. it returns the result of foo.equals(bar)

Related

RegEx that captures a method and its body [duplicate]

This question already has answers here:
Java : parse java source code, extract methods
(2 answers)
Closed 1 year ago.
I have tried to develop a regex that captures a method and its body (The modifier is not important), but I could not develop a solid solution. The regex that I came up with so far is this: \\b\\w*\\s*\\w*\\s*\\(.*?\\)\\s*\\{([^}]+)\\}
It does not capture the methods correctly because it does not consider matching balanced Curley braces. Thus, sometimes it captures part of the method and not all. What am I doing wrong or what could I do to improve the solution that can capture the whole method!
You can't do this. It's impossible.
The 'regular' in 'Regular Expression' refers to a certain subset of grammars; the so-called 'Regular Grammars'.
Here's the thing:
Non-Regular Grammars cannot be parsed with regular expressions.
Java (the language) is Non-Regular.
Thus, you can't use regular expressions for this, QED.
So, how do you parse java?
There are many ways; so far, java is still so-called LL(k) parseable, which means that just about every 'parser/grammar' library out there will be capable of parsing java code, and many such libraries ship with a java grammar as an example. These usually aren't quite perfect, but pretty good.
A basic web search gets you many options. Alternatively, javac is free (but GPL, you'd have to GPL anything you build with it), and ecj (the parser that powers eclipse, amongst other things) is open source with a more permissive license. It's also faster. It's also far harder to use, so there's that.
These are fairly complex tools. However, java is a very complex language (much programming languages are). Parsing them is decidedly non-trivial.
Before you think: Geez, surely it can't be this hard, consider:
public void test {
{}
String x = "{";
}
Which is legal java.
Or:
public void test() {
// method body
\u007D
That really is legal java, that \u007D thing closes it. Of course...
public void test() {
//{} \u007D
}
Here the \u thing doesn't. It is a real closing brace, but, that is in a comment.
Another one to consider:
public void test() {
class Foo {
String y = """
}
""";
}
}
Hopefully, considering the above, you realize you stand absolutely no chance whatsoever unless you use a parser that knows about the entire language spec.

java annotation with argument named default [duplicate]

Is there any tricky way to use Java reserved words as variable, method, class, interface, package, or enum constant names?
This is a valid question. Such a thing is possible in other languages. In C#, prefix the identifier with # (as asked before); in Delphi, prefix with &. But Java offers no such feature (partly because it doesn't really need to interact with identifiers defined by other languages the way the .Net world does).
No, there is no way. That's why they're labeled "reserved".
Most often this issue comes up for "class", in this case it is customary to write "clazz".
Strictly speaking you can't, unless you get your hands on a buggy compiler implementation that doesn't adhere to the Java language spec.
But where there's a will, there's a way. Copy the following code into your IDE, switch the source file encoding to UTF-16 and here we go:
public class HelloWorld {
public static void main(String[] args) {
HelloWorld.nеw();
}
public static void nеw () {
System.out.println("Hello,World");
}
}
This code is a well-formed and valid Java class. However, as you have guessed there is a little trick: the 'е' character within "new" identifier does not belong to the ASCII character set, it is actually a cyrrilic 'е' (prounanced 'YE').
Current Java language spec explicitly permits, and this an important point to make, the use of Unicode for naming identifiers. That means that one has an ability to freely call her or his classes in French, Chinise or Russian if they wish. It is also possible to mix and match the alphabets within code. And historically, some letters within Latin and other alphabets are lookalikes.
As a result: no, you can't use the reserved words as identifiers, but you can use identifiers that look exactly like reserved words.
Whether anyone should be doing it is a totally different matter.
No, you can't do this. For more information please go to JLS Sections 3.8, 3.9
The following character sequences,
formed from ASCII letters, are
reserved for use as keywords and
cannot be used as identifiers (§3.8):
Keyword: one of
abstract continue for new switch
assert default if package synchronized
boolean do goto private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const float native super while
Yes, there is.
You have to use reserved words from the future.
Like what happened with different methods called assert() in pre-1.4 code.
Hope it helps!
In Scala you can use backticks. For example: myVarialbe.`class`
Not sure what you're trying to do, but $ is a valid character in identifiers, so you could do, say:
int $return = 5;
It looks a little weird, but it does work.
I know it's old question still, might help someone.
It's possible by using GSON's Field Naming Support
eg.
#SerializedName("new")
private String New;
public String getNew ()
{
return New;
}
public void setNew (String aNew)
{
New = aNew;
}
Huh? Why would you want to do that? You can write them in l33t, that will fool the compiler.
class cl4ss {
String r3turn() {
return "but why?";
}
}
There is no way to use reserved words with the javac compiler.
Technically, you can edit the names inside the class file once it's compiled to be anything you want: at that stage, the VM doesn't care, because it's not dealing with source code any more. I believe some obfuscators use this technique.
PL/1 (a 1960's IBM mainframe programming language still around today) rather famously required that while some words act like keywords in certain contexts, all words can be used as identifiers. This isn't even that hard to do in a parser if you set out to be consistent about it. PL/1 was considered to a rather big langauge, and the langauge committee worried that many programmers wouldn't learn all of it, and then would get suprised when they tried to use the keyword from a part they didn't know as an identifier.
So you could write things like:
IF BEGIN=ELSE THEN CALL=3 ELSE CALL FOO(ENDIF) ENDIF
As others have noted here, the ability to do this isn't a recommendation.
The Java designers decided the number of keywords in the langauge was modest, and reserved the set. They even reserved 'GOTO', which isn't actually allowed in any real Java program.
If you really need to use a field/local variable/method named the same as a reserved word, I suggest appending an underscore at the end of the name:
// JPA entity mapping class:
private Boolean void_;
public Boolean getVoid_() { ... }
void setVoid_(Boolean void_) { ... }
It is a more readable choice (IMHO) than appending chars at the beginning of the name (fVoid, aVoid, vVoid, etc.)
The code above is a real world case that happened to me, working with a legacy database, in which the invoice table had a field named void indicating whether the document had been voided or not.

What can I do in Scala that I could not do in Java? [duplicate]

This question already has answers here:
What Are The Benefits Of Scala? [closed]
(5 answers)
Java 8 and Scala [closed]
(8 answers)
Closed 9 years ago.
I am reading about Scala here and there but I could not understand what would a Java developer gain from jumping on Scala.
I think it is something to do with functional programming.
Could someone please give me a concrete example of something I can not do in Java and going to Scala would save me?
This is not intented to be a critique on Java or something similar.I only need to understand the usage of Scala
I'm also jumping from Java's world, the first thing that I think will save you is that Scala has a lot of compiler magic that helps you to keep your code simple and clean.
For example, the following is how Scala's case class will help you, we could define a class using this:
case class Student(name: String, height: Double, weight: Double)
instead of this:
class Student {
public final String name;
public final String height;
public final String weight;
public Student(String name, double height, double weight) {
this.name = name;
this.height = height;
this.weight = weight;
}
}
Yes, that is all, you don't need write constructor yourself, and you have all those equals, hasCode, toString method for free.
It may looks like not a big deal in this simple case, but Scala really make you to model things a lot easier and quicker in OO, even if you are not using functional programming construct.
Also, high-order function and other functional programming construct will also give you powerful tools to solve your problem in Scala.
Update
OK, the following is a example of how functional programming will make your code more easier to understand and clean.
Functional programming is a large topic, but I found that even I'm from Java's world and does not understand what is monad or typeclass or whatever, Scala's functional programming construct is still help me to solve problem more easily and more expressive.
There are many times we need to iterate over a collection and do something to the elements in the collection, depends on a condition to decide what to do.
For a simple example, if we want to iterate over a List in java, and delete all file that size are zero. What we will do in Java maybe looks like the following:
List<File> files = getFiles()
for (File file: files) {
if (file.size() == 0) {
file.delete();
}
}
It's very easy and concise, isn't it? But with functional programming construct in Scala, we could do the following:
val files = getFiles()
val emptyFiles = files.filter(_.size == 0)
emptyFiles.foreach(_.delete())
As you can see, it has less code than the Java's version, and out intention is even clear -- we want filter out all files that size is 0, and for all of it, call File.delete() on it.
It may looks weird at first, but once you get used to it and use it in right way, it will make your code a lot easier to read.
The technique is possible in Java (Function Java), but in the end it will looks like the following code:
list.filter(new Predicate<File>() {
public boolean predicate(File f) {
return f.size() == 0;
}
})
Which I'll just stick to the origin for-loop version, IMHO.
To get you started, this article by Graham Lea lists many ways that Scala can boost your productivity:
A New Java Library for Amazing Productivity.
It begins with:
a broad and powerful collections framework
collection methods that greatly reduce boilerplate
immutable collections that don’t have mutation methods (unlike java.util classes where e.g. List.add() throws an exception if the list is immutable)
an awesome switch-like function that doesn’t just match numbers, enums, chars and strings, but can succinctly match all kinds of patterns in lots of different classes, even in your own classes
an annotation that automatically writes meaningful equals, hashCode and toString methods for classes whose fields don’t change (without using reflection)
...
and the list goes on.
To be specific on your question:
in scala you can pattern match
scala has higher order functions (which is not the same as java8 lambdas)
anonymous function literals
strong type inference
lazy evaluation
variance annotation
higher kinded types
mixin behavior with traits (stackable composition)
implicit definition and conversion
xml literals
REPL
I could go on but I urge you to read at least some documentation.
For instance you can start here
Functional programming is the most brief and accurate statement. This and the shorter more expressive code that scala promotes translates to higher productivity.
Scala is also more Conscisce
There are also several other examples of this.

Java -> Python?

Besides the dynamic nature of Python (and the syntax), what are some of the major features of the Python language that Java doesn't have, and vice versa?
List comprehensions. I often find myself filtering/mapping lists, and being able to say [line.replace("spam","eggs") for line in open("somefile.txt") if line.startswith("nee")] is really nice.
Functions are first class objects. They can be passed as parameters to other functions, defined inside other function, and have lexical scope. This makes it really easy to say things like people.sort(key=lambda p: p.age) and thus sort a bunch of people on their age without having to define a custom comparator class or something equally verbose.
Everything is an object. Java has basic types which aren't objects, which is why many classes in the standard library define 9 different versions of functions (for boolean, byte, char, double, float, int, long, Object, short). Array.sort is a good example. Autoboxing helps, although it makes things awkward when something turns out to be null.
Properties. Python lets you create classes with read-only fields, lazily-generated fields, as well as fields which are checked upon assignment to make sure they're never 0 or null or whatever you want to guard against, etc.'
Default and keyword arguments. In Java if you want a constructor that can take up to 5 optional arguments, you must define 6 different versions of that constructor. And there's no way at all to say Student(name="Eli", age=25)
Functions can only return 1 thing. In Python you have tuple assignment, so you can say spam, eggs = nee() but in Java you'd need to either resort to mutable out parameters or have a custom class with 2 fields and then have two additional lines of code to extract those fields.
Built-in syntax for lists and dictionaries.
Operator Overloading.
Generally better designed libraries. For example, to parse an XML document in Java, you say
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("test.xml");
and in Python you say
doc = parse("test.xml")
Anyway, I could go on and on with further examples, but Python is just overall a much more flexible and expressive language. It's also dynamically typed, which I really like, but which comes with some disadvantages.
Java has much better performance than Python and has way better tool support. Sometimes those things matter a lot and Java is the better language than Python for a task; I continue to use Java for some new projects despite liking Python a lot more. But as a language I think Python is superior for most things I find myself needing to accomplish.
I think this pair of articles by Philip J. Eby does a great job discussing the differences between the two languages (mostly about philosophy/mentality rather than specific language features).
Python is Not Java
Java is Not Python, either
One key difference in Python is significant whitespace. This puts a lot of people off - me too for a long time - but once you get going it seems natural and makes much more sense than ;s everywhere.
From a personal perspective, Python has the following benefits over Java:
No Checked Exceptions
Optional Arguments
Much less boilerplate and less verbose generally
Other than those, this page on the Python Wiki is a good place to look with lots of links to interesting articles.
With Jython you can have both. It's only at Python 2.2, but still very useful if you need an embedded interpreter that has access to the Java runtime.
Apart from what Eli Courtwright said:
I find iterators in Python more concise. You can use for i in something, and it works with pretty much everything. Yeah, Java has gotten better since 1.5, but for example you can iterate through a string in python with this same construct.
Introspection: In python you can get at runtime information about an object or a module about its symbols, methods, or even its docstrings. You can also instantiate them dynamically. Java has some of this, but usually in Java it takes half a page of code to get an instance of a class, whereas in Python it is about 3 lines. And as far as I know the docstrings thing is not available in Java

Does Java need closures?

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". Can anyone give me a specific use-case where a closure would be needed (or even preferred)?
As a Lisp programmer I would wish that the Java community understands the following difference: functions as objects vs. closures.
a) functions can be named or anonymous. 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.
Anonymous functions don't add much to the language, they just allow you to write functions in a shorter way.
b) A closure is a function plus a binding environment. Closures can be passed downwards (as parameters) or returned upwards (as return values). This allows the function to refer to variables of its environment, even if the surrounding code is no longer active.
If you have a) in some language, then the question comes up what to do about b)? There are languages that have a), but not b). In the functional programming world a) (functions) and b (functions as closures) is nowadays the norm. Smalltalk had a) (blocks are anonymous functions) for a long time, but then some dialects of Smalltalk added support for b) (blocks as closures).
You can imagine that you get a slightly different programming model, if you add functions and closures to the language.
From a pragmatic view, the anonymous function adds some short notation, where you pass or invoke functions. That can be a good thing.
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 lexical variable (that can be accessed in a closure) and when should it be a variable of some object (a slot). 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.
The result is a more complicated programming language and a more complicated runtime model. Too complicated?
They don't make an Object-Oriented language better. They make practical languages more practical.
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.
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".
Fantastic stuff.
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.
So do we need closures? No. Would they be nice to have? Sure, as long as they don't feel bolted on, as I fear they would be.
I suppose for supporting core functional programming concepts, you need closures. Makes the code more elegant and composable with the support for closures. Also, I like the idea of passing around lines of code as parameters to functions.
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.
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 Groovy).
For example to square each element in a list without closures you would probably write:
List<Integer> squareInts(List<Integer> is){
List<Integer> result = new ArrayList<Integer>(is.size());
for (Integer i:is)
result.add(i*i);
return result;
}
Using closures and map and the proposed syntax, you could write it like that:
is.map({Integer i => i*i})
(There is a possible performance problem here regarding boxing of primitive types.)
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:
Instead of:
void onlyStringsWithMoreThan4Chars(List<String> strings){
List<String> result = new ArrayList<String>(str.size()); // should be enough
for (String str:strings)
if (str.length() > 4) result.add(str);
return result;
}
Instead you could write something like
strings.select({String str => str.length() > 4});
using the proposal.
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 Groovy User Guide for more examples what to do with closures.
A remark:
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'.
A 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:
Runnable createStringPrintingRunnable(final String str){
return new Runnable(){
public void run(){
System.out.println(str); // this accesses a variable from an outer scope
}
};
}
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).
But closures are desirable as a feature because they greatly simplify the code and increase readability and as a consequence the maintainability of the code.
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:
// Example #1 with closures
public IList<Customer> GetFilteredCustomerList(string filter) {
//Here a closure is created around the filter parameter
return Customers.Where( c => c.Name.Contains(filter)).ToList();
}
now take an equivalent example that doesn't use closures
//Example #2 without closures, using just basic OO techniques
public IList<Customer> GetFilteredCustomerList(string filter) {
return new Customers.Where( new CustomerNameFiltrator(filter));
}
...
public class CustomerNameFiltrator : IFilter<Customer> {
private string _filter;
public CustomerNameFiltrator(string filter) {
_filter = filter;
}
public bool Filter(Customer customer) {
return customer.Name.Contains( _filter);
}
}
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.
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.
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."
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.
For example, in Python:
def reversecmp(x, y):
return y - x
a = [4, 2, 5, 9, 11]
a.sort(cmp=reversecmp)
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:
a = [4, 2, 5, 9, 11]
a.sort(cmp=lambda x, y : y - x)
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:
class ReverseComparator implements Comparator {
public compare(Object x, Object y) {
return (Integer) y - (Integer) x;
}
...
List<Integer> a = Arrays.asList(4, 2, 5, 9, 11);
Collections.sort(a, new ReverseComparator());
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:
List<Integer> a = Arrays.asList(4, 2, 5, 9, 11);
Comparator reverse = new Comparator() {
public Compare(Object x, Object y) {
return (Integer) y - (Integer) x;
}
}
Collections.sort(a, reverse);
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.
Java has had closures since 1.1, just in a very cumbersome and limited way.
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.
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.
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.
When closures finally arrive in Java, I will gleefully get rid of all my custom comparator classes.
myArray.sort( (a, b) => a.myProperty().compareTo(b.myProperty() );
...looks a helluva lot better than...
myArray.sort(new Comparator<MyClass>() {
public int compare(MyClass a, MyClass b) {
return a.myProperty().compareTo(b.myProperty();
}
});
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.
They are 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.
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.
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. I wrote a blog entry on exactly that subject a couple of years ago when I first heard closures might be coming.
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.
I have been thinking a lot about the topic of this very interesting question in
the last few days. First of all, if I have understood correctly, Java already has
some basic notion of closures (defined through anonymous classes) but the new feature
that is going to be introduced is the support for closures based on anonymous functions.
This extension will definitely make the language more expressive but I am not sure
if it really fits with the rest of the language.
Java 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?
My impression is that as new programming styles or paradigms like functional
programming become more popular, everyone wants to use them in their
favourite OOP language. This is understandable: one wants to continue to use
a language they're familiar with while adopting new features. But in this way
a language can become really complex and lose coherence.
So my attitude at the moment is to stick to Java 6 for OOP (I hope Java 6 will still
be supported for a while) and, in case I really get interested in doing OOP + FP,
to take a look at some other language like Scala (Scala was defined to be multi-
paradigm from the beginning and can be well integrated with Java) rather than switching
to Java 7.
I think Java owes its success to the fact that it combines a simple language with very
powerful libraries and tools, and I do not think that new features like closures will
make it a better programming language.
Now that JDK8 is about to be released there is more information available that can enrich the answers to this question.
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 around January 2013 and should be released around midyear 2013.
The State of Lambda: 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.
The State of Lambda - Libraries Edition: this is also very interesting because it covers advantages like lazy evaluation and parallelism.
The Translation of Lambda Expressions: which basically explains the desugaring process done by the Java compiler.
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.
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 final variables.
Almost any language feature can be criticised as non-essential:
for, while, do are all just syntactic sugar over goto/if.
Inner classes are syntactic sugar over classes with a field pointing to the outer class.
Generics are syntactic sugar over casts.
Exactly the same "non-essential" argument should have blocked the inclusion of all the above features.
Java Closure Examples
Not only that benjismith, but I love how you can just do...
myArray.sort{ it.myProperty }
You only need the more detailed comparator you've shown when the natural language comparison of the property doesn't suit your needs.
I absolutely love this feature.
What about readability and maintainability...one-liner closures are harder to understand and debug, imo
Software 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...
You might want to look at Groovy, a language that's mostly compatible with Java, and runs on the JRE, but supports Closures.
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 final then they are available but not otherwise], I don't quite understand what that restriction actually buys.
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).
If the closure wants to overwrite the reference, so be it; it will do so without changing the copy that the enclosing scope sees.
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?

Categories