First Release for Groovy 1.0: JVM Scripting Language

Discussions

News: First Release for Groovy 1.0: JVM Scripting Language

  1. The first release of Groovy has appeared in the CodeHaus. Checkout Groovy 1.0beta. "Groovy is a powerful new high level dynamic language for the JVM combining lots of great features from languages like Python, Ruby and Smalltalk and making them available to the Java developers using a Java-like syntax."

    This release includes:

    - compile time or runtime compilation straight to Java bytecode as well as groovyc Ant task and command line script
    - a Swing based console (groovyConsole) and a simple command line terminal (groovysh) complete with typeo :)
    - full support for properties, fields, native syntax for maps, lists, regex and autoboxing
    - 'true' closures (like Ruby 2.0), static or dynamic typing, operator overloading, text templating
    - GPath (a native XPath like language)
    - GroovyMarkup for embedding structured markup inside Groovy with support for markup, DOM, SAX, Swing and Ant scripting
    - Groovlets - a neat way of writing Servlets using groovy

    Resources

    Groovy 1.0-beta-1 is out!

    Groovy Home Page

    Download Groovy

    Example Groovy Script

    Notice that Groovy is dynamically typed, has closure support and supports something similar to Python's tuple / sequence / dictionary support (List and Map in Java)

    class Foo {
      doSomething() {
        data = ["name": "James", "location": "London"]
        for (e in data) {
          println("property ${e.key} is ${e.value}")
        }
      }
      
      closureExample(collection) {
        collection.each { println("value ${it}") }
      }
      
      static void main(args) {
        values = [1, 2, 3, "abc"]
        closureExample(values)
      }
    }

    Threaded Messages (47)

  2. question ?[ Go to top ]

    is this kinda equal to Microsoft's WSH?
  3. question ?[ Go to top ]

    is this kinda equal to Microsoft's WSH?


    Maybe. Groovy is much more concise. Groovy also introduces some cool language elements - for example, native constructs for maps and lists, and GPath. And Groovy compiles to bytecode.

    Sandeep.
  4. question ?[ Go to top ]

    And Groovy compiles to bytecode.


    (Splitting hairs) It compiles to Java (which compiles to bytecode), no?

    -Nick
  5. question ?[ Go to top ]

    And Groovy compiles to bytecode.

    >
    > (Splitting hairs) It compiles to Java (which compiles to bytecode), no?

    No - it compiles straight to bytecode either at compile time or runtime. There's no 'java' intermediate form.

    http://groovy.codehaus.org/compiling.html

    Though there's no reason why someone couldn't write a little AST walker to generate Java source code but we've not done that yet as so far there's been no demand it.

    James
    Core Developers Network
  6. Very, very cool. Sounds pretty seamless.
    Steve
  7. Compared with BSF?[ Go to top ]

    Whats the advantage of this over BSF?

    Billy
  8. Compared with BSF?[ Go to top ]

    Whats the advantage of this over BSF?


    BSF is a framework for invoking any scripting language - BSF is not actually a scripting language itself. Groovy fully supports BSF. So if you want to integrate any scripting language into your app, you could use BSF and then you can plug and play Jython, Rhino, BeanShell, Groovy etc.

    Though Groovy allows you to have a much tigher integration from Java if you wish i.e. scripts easily parse directly into Java clases & groovy objects are java objects you can work with directly. So depending on your requirements the BSF level of indirection may or may not be a good thing - its your choice.

    James
    Core Developers Network
  9. Compared with BSF?[ Go to top ]

    Whats the advantage of this over BSF?

    >
    > Billy

    Maybe you're thinking of BeanShell?

    BeanShell is pretty nice actually. The current 2.0 (beta) version can take basically _any_ java code and run it dynamically. It is also dynamic to the extent that you don't have to do variable declarations, etc.

    What I like about Groovy though is all the syntactical sugar, and extra features like closures. Running java code dynamically is nice, but if it's basically straight java (minus variable decls) you are still typing a lot. Groovy's shortcuts for producing maps and lists, along with other features like closures and the like, can really reduce some of that typing. I do wish they would add some extra (Python like) syntax sugar for less verbose imports, along the lines of:

    import Xxxxx, Yyyyy, Zzzz from java.util;

    or

    from java.util import Xxxxx, Yyyyy, Zzzzz;

    Regards,
    Colin
  10. Compared with BSF?[ Go to top ]

    I do wish they would add some extra (Python like) syntax sugar

    > for less verbose imports, along the lines of:
    >
    > import Xxxxx, Yyyyy, Zzzz from java.util;
    >
    > or
    >
    > from java.util import Xxxxx, Yyyyy, Zzzzz;
    >
    > Regards,
    > Colin

    Great suggestion Colin, I've added your wish to the issue tracker...

    http://jira.codehaus.org/secure/ViewIssue.jspa?key=GROOVY-80

    James
    Core Developers Network
  11. Compared with BSF?[ Go to top ]

    BTW talking about import statements, one neat thing about imports in groovy is you can rename classes logically in your code; so you can simplify your code. e.g.

    import java.util.Date
    import java.sql.Data as SqlDate
    import blah.SomeReallyLongImplementationClass as Foo

    // no need for fully qualified class names...
    x = new Date()
    y = new SqlDate()

    // less typing
    z = new Foo(123)

    James
    Core Developers Network
  12. import as[ Go to top ]

    BTW talking about import statements, one neat thing about imports in groovy is you can rename classes logically in your code; so you can simplify your code. e.g.

    import java.util.Date
    import java.sql.Data as SqlDate
    import blah.SomeReallyLongImplementationClass as Foo


    That's a very handy feature to have. We have used the same thing in our own model compiler since '98, and it's hard to live without now ;-).

    Peace,

    Cameron Purdy
    Tangosol, Inc.
    Coherence: Clustered JCache for Grid Computing!
  13. Compared with BSF?[ Go to top ]

    BTW talking about import statements, one neat thing about imports in groovy is you can rename classes logically in your code; so you can simplify your code. e.g.

    >
    > import java.util.Date
    > import java.sql.Data as SqlDate
    > import blah.SomeReallyLongImplementationClass as Foo

    So the wheel turns.. pick a define from good old C.

    > // no need for fully qualified class names...
    > x = new Date()
    > y = new SqlDate()

    The changes of encountering such a situation are like one in a million? When that risk evaluates, It's much better to be prepared with 2nd. generation define than write that extra 4 letters and 2 dots. Writing sucks.

    > // less typing
    > z = new Foo(123)
    >
    > James

    Yeah! It's so much more cool to write:
    [code]
    z = new Foo(123);
    y = new Bar();
    y.fiz(z);

    // than
    Constraint c = new TypeConstraint(123);
    Query qry = new QueryBuilder();
    qry.addConstraint(c);
    [/code]
    Because the latter is so lame. And we're all using notepads to write code.

    Man I hate that ctrl+space thingy in IDEA where the stupid editor writes the code for me. It's also boring to see that stupid method list pop up with all those expressive method names that just point you to right direction. It'd be much nicer to see a long list of foo's and bar's come up!

    Pressure down - end of rant.
  14. Compared with BSF?[ Go to top ]

    BTW talking about import statements, one neat thing about imports in groovy is you can rename classes logically in your code; so you can simplify your code. e.g.

    > >
    > > import java.util.Date
    > > import java.sql.Data as SqlDate
    > > import blah.SomeReallyLongImplementationClass as Foo
    >
    > So the wheel turns.. pick a define from good old C.

    shudder :). We've just chosen to use a really simple kind of define constrained just for imports to avoid making code hard to read.


    > Yeah! It's so much more cool to write:
    > [code]
    > z = new Foo(123);
    > y = new Bar();
    > y.fiz(z);
    >
    > // than
    > Constraint c = new TypeConstraint(123);
    > Query qry = new QueryBuilder();
    > qry.addConstraint(c);
    > [/code]
    > Because the latter is so lame. And we're all using notepads to write code.
    >
    > Man I hate that ctrl+space thingy in IDEA where the stupid editor writes the code for me. It's also boring to see that stupid method list pop up with all those expressive method names that just point you to right direction. It'd be much nicer to see a long list of foo's and bar's come up!
    >
    > Pressure down - end of rant.

    :)

    Its a good point. Groovy supports both static typing and dynamic typing; its your choice as a developer. i.e. you can make everything statically typed if you want to create a typesafe API. Or if you're writing some script or glue code (or a unit test case) you can leave out typing if you like.

    So if you want all the IDE refactoring goodness, use static typing but take advantage of all the neat new syntax for properties, lists, maps, beans, events, autoboxing, mixins and so forth.

    Ultimately I'd like Groovy to use type inference; so that even when you're in dynamic typing mode you could have the same kind of refactoring ability as when being statically typed.

    James
    Core Developers Network
  15. Keyword 'new', Compared with BSF?[ Go to top ]

    It's so much more cool to write:
     z = new Foo(123);
     y = new Bar();
     y.fiz(z);


    While we're on the topic of terse syntax, I wish the keyword 'new' were eliminated and instead implicit. Constructor invocation is still unambiguous without it.
  16. public class MethodOrConstructor {
      public MethodOrConstructor() {
        System.out.println("Constructor");
      }
      public static MethodOrConstructor MethodOrConstructor() {
        System.out.println("Method");
        return new MethodOrConstructor();
      }
      public static void main(String[] args) {
        MethodOrConstructor m = MethodOrConstructor();
      }
    }

    /Users/sam/weblogic/dev/src:> javac /tmp/MethodOrConstructor.java
    /Users/sam/weblogic/dev/src:> java -cp /tmp MethodOrConstructor
    Method
    Constructor
    /Users/sam/weblogic/dev/src:>

    Unfortunately, they are not. Even worse, I have had the pleasure of actually seeing code that does this for singletons.

    Sam
  17. Compared with BSF?[ Go to top ]

    import java.sql.Data as SqlDate


    This is a perfect recepie for ensuring that your code will not be
    readeable by anyone but yourself. Every developer will have their
    own version: SDate, JSqlDate, SqlDateThingy, Date, etc.
  18. Compared with BSF?[ Go to top ]

    import java.sql.Data as SqlDate

    >
    > This is a perfect recepie for ensuring that your code will not be
    > readeable by anyone but yourself. Every developer will have their
    > own version: SDate, JSqlDate, SqlDateThingy, Date, etc.

    Only if the developers are goofy enough to use the feature in an inappropriate way, like renaming renaming classes when there is no naming conflict. (And if that is the case, the feature isn't the problem).
  19. Looks Great[ Go to top ]

    Groovy looks very promising! There's no doubt that we can improve upon many of the capabilities of languages like Java and C#, and Groovy seems to be heading in the right direction. Allowing it to run directly on a JVM is a smart move; any thoughts of getting it to run on CLR as well?

    Cheers,
    Graham
  20. Looks Great[ Go to top ]

    Allowing it to run directly on a JVM is a smart move; any thoughts of getting it to run on CLR as well?

    >
    > Cheers,
    > Graham

    Hi Graham

    Funnily enough a few folks have asked for that. The language has been designed so it should sit just as neatly on top of .Net as well as the JVM (or any VM really, like Parrot too) - the basic design idea is to be native on the underlying VM and let the VM's platform APIs shine through, but add some groovy-ness to it. i.e. preserve the underlying platform, just make it more groovy. So rather than ditching all of .Net or the Java platform for Ruby or Python, keep the platform & APIs & code you're using and just make it neater.

    e.g. the Groovy Development Kit (GDK) is a small layer on top of the JDK which adds some nice new behaviour.

    http://groovy.codehaus.org/apidocs/index.html

    though we can also add some nice methods/APIs to existing JDK classes and fix the odd bit of inconsistency here and there (e.g. List.size() and String.size()). e.g.

    http://groovy.codehaus.org/quickStart.html


    There's no real reason why the Groovy compiler couldn't spit out CLR code - you could easily walk the AST of Groovy & generate it fairly simply. Though runtime compilation is where the fun is (e.g. groovylets as an alternative to JSP / Velocity) so you'd probably want a .Net equivalent of the parser & GroovyClassLoader to run in-process in .Net.

    If someone had a Java 2 -> .Net conversion tool (a bit like the old JDK 1.1.8 tool) then it should just work today on .NET, probably :). Getting a native runtime for dynamic method invocation and so forth would take a little bit of work; but its not a massive amount of work. Afterall Groovy's only been going for about 5 months part time so far; so porting all this to .Net should be fairly quick.


    James
    Core Developers Network
  21. Support for JSR 45[ Go to top ]

    Hi,

    Is groovy 1.0 going to support JSR 45 Debugging Support for Other Languages?

    I think it will be very useful if I can debug groovy script with any IDE supports JSR 45.
  22. Support for JSR 45[ Go to top ]

    Is groovy 1.0 going to support JSR 45 Debugging Support for Other Languages?

    >
    > I think it will be very useful if I can debug groovy script with any IDE supports JSR 45.

    Totally agree

    http://jira.codehaus.org/secure/ViewIssue.jspa?key=GROOVY-63

    :)

    James
    Core Developers Network
  23. Support for JSR 45[ Go to top ]

    It must be possible to debug groovy with any IDE and debuger, It is the same code as produced by javac, emit debug info (line number mappings, source file, local names) and it must work without new JSRs.
  24. Support for JSR 45[ Go to top ]

    It must be possible to debug groovy with any IDE and debuger, It is the same code as produced by javac, emit debug info (line number mappings, source file, local names) and it must work without new JSRs.


    Line number information is there in the bytecode & stack traces when exceptions are thrown; though I'm wondering if JSR 45 support will allow breakpoints to be set inside groovy source code etc.

    James
    Core Developers Network
  25. Support for JSR 45[ Go to top ]

    Breakpoints must not be a problem too.
    JVM fires BreakpointEvent with Location, it comes from class file debug info and as I understand source can be any file, not existing file must be OK too.
    I have never tried it in practice, but I have plans to debug dynamicly generated classes this way ( to use something like javap format for source ).
    Looks like it is SUN's JVM specific API, but class format is the same for all implementations. I do not know about JSR 45, but it is API, is not it ?
    This kind of API is usefull for "scripting" languages, but as I understand groovy is the same JAVA, just source file format (syntax) is changed.
  26. Just to let you know I've put up a "Scripting Language for Java of the Year 2003" poll over at the Java Republic news blog. Vote for Groovy today.

    The contenders are:

    * Jython (Python for Java)
    * BeanShell (Dynamic Java)
    * Groovy
    * Jacl (Java Command Language)
    * Rhino (JavacScript )
    * JRuby (Ruby for Java)
    * Bistro (Smalltalk for Java)
    * Kawa (Lisp/Scheme for Java)
    * Jelly
    * Simkin

    So far Groovy's showing is impressive. Groovy is in third postition holding 25 votes and trailing the Jython King of the Hill with 60 votes and BeanShell with 40.
  27. What about JudoScript?[ Go to top ]

    No vote option for http://www.judoscript.com/index.html ? It's LGPL and has very nice declarative features.
  28. JudoScript[ Go to top ]


    > It's LGPL and has very nice declarative features.

      The pollhost.com service limits the choices to ten contenders. Sorry for leaving out JudoScript and thanks for pointing it out. I will add JudoScript to the Viva! scripting language page and consider it for next year's Viva! Scripting Language for Java of the Year Award.

      - Gerald
  29. Hi,

      Thanks to everybody who already voted for Groovy in the "Scripting Language for Java of the Year 2003" poll over at the Java Republic news blog. If you haven't cast your vote yet, why not do so today?

      Here's the standing as of Dec. 15:

      #1 - Jython (Python for Java) - 146 votes (46%)
      #2 - Groovy - 65 votes (21%)
      #3 - Beanshell - 60 votes (19%)
      #4 - Rhino (Javascript) - 21 votes (7%)
      #5 - JRuby (Ruby for Java) - 8 votes (3%)
      and so on
  30. Absolutely useful![ Go to top ]

    Groovy has the potential to be absolutely useful!

    Given Groovy's treatment of stuff like xml as a first-class language citizen, Groovy could be very useful for web services scripting.

    Groovy could definitely make it much easier to script OpenOffice documents via the OpenOffice API. Currently, the Java binding for the api is too much of pain to use. But as the new Python-based binding for the api demonstrates, scripting the API is a relative breeze.

    Perhaps Groovy could emerge as an enabler for building the types of accessible (e.g. no build steps required) high-level functionality that is commonplace in the PHP world.
  31. Documention...?[ Go to top ]

    Browsing the Groovy site I couldn't find a guide to the syntax used in this release (there are discussion threads detailing various alternatives, but no definitive guide). A BNF would be very useful.

    Jonathan
  32. Documention...?[ Go to top ]

    Browsing the Groovy site I couldn't find a guide to the syntax used in this release (there are discussion threads detailing various alternatives, but no definitive guide). A BNF would be very useful.


    Agreed. Apologies, the documentation is quite light right now; we'll try sort that out in the next few weeks.

    James
    Core Developers Network
  33. Refactoring, Debugging, IDE support???[ Go to top ]

    What about Refactoring, Debugging, IDE support???
  34. Refactoring, Debugging, IDE support???[ Go to top ]

    What about Refactoring, Debugging, IDE support???


    Whilst its not had a binary release yet, there's an inital eclipse plugin in CVS...

    http://cvs.groovy.codehaus.org/viewcvs.cgi/groovy/groovy-eclipse/?root=codehaus

    Its fairly simple right now, supporting syntax highlighting & evaluation of whole or selections of groovy scripts.

    Just yesterday a thread started on the groovy-dev mail list about creating an IntelliJ plugin.

    I'd love both Eclipse and IntelliJ to support refactoring of Java and Groovy code in the same project.

    e.g. use Groovy for your glue code, for scripting stuff, for you UI layout, for your templates (groovlets) or unit test cases, but still use Java for your business logic and refactor seamlessly across both languages. Its all Java underneath anyways; we've just gotta spoof the IDEs into thinking its all Java...

    James
    Core Developers Network
  35. Groovy, Jython, and JSR 223[ Go to top ]

    I'm going to check out Groovy. It sounds great. I'm a big supporter of Jython (http://www.jython.org) so it will be interesting to see how they compare.

    I really like the idea that Groovy compiles its scripts to Java byte codes. Groovy is more evidence to me that JSR 223 is a bad idea. JSR 223 is supposed to describe mechanisms for scripting language programs to access Java programs, especially server-side applications. It appears to me to mostly be a way to give PHP users a way to use Java. Since PHP does not compile into byte codes, a native interface is going to be needed. And that will likely bring along scalability, performance, and portability problems.

    It is clear to my from Groovy and Jython's example that script languages that compile into Java byte codes is a good thing.

    -Frank Cohen
    http://www.pushtotest.com/ptt
    TestMaker 4.0.6 now available

    Details on JSR 223 are at:
    http://www.jcp.org/en/jsr/detail?id=223&showPrint
  36. Groovy, Jython, and JSR 223[ Go to top ]

    I guess there goes Jython. I was always impressed by the source code for this project - it is really good. However, time to move on. It sounds like Groovy is more seamless with Java.
  37. Groovy, Jython, and JSR 223[ Go to top ]

    I guess there goes Jython.

    Totally. I think the Java Language Specification is also made obsolete by Groovy. If Groovy runs on Kaffe, then we don't need Sun anymore.
  38. Groovy, Jython, and JSR 223[ Go to top ]

    There is a nice irony if you go to the Groovy Wiki - look at the bottom of the page and it says Python Powered! Now just how long will it take for the Groovy community to start building the types of infrastructure that made Python what it is: the libraries, Mailman, Zope, and Plone???
  39. Groovy, Jython, and JSR 223[ Go to top ]

    There is a nice irony if you go to the Groovy Wiki - look at the bottom of the page and it says Python Powered! Now just how long will it take for the Groovy community to start building the types of infrastructure that made Python what it is: the libraries, Mailman, Zope, and Plone???

    Only a very few years ago, some folks were insisting that Perl wouldn't be supplanted any time soon. Internet time is amazing. Python's coup was rather swift. And Python didn't even introduce anything original in language design. Groovy is ready for the XML tidal wave (SVG, WSDL, Ant, X3D, OWL, etc) in ways that Java and Python aren't. The World Wide Web Consortium recently announced its "Architecture of the World Wide Web, First Edition". The References section reads like a punch list of technologies that Groovy could kick azz at. I think maybe I've been around long enough to recognize a winner before the race completes. Give Groovy continuations and tight XSL integration by embedding Groovy into Cocoon, and there's an unbeatable work flow engine for silly things such as BPEL or a reliable client. I can't think of a better GUI architecture than an XML document player with inlined Groovy scriptlets. Can you?
  40. Groovy is ready for the XML tidal wave (SVG, WSDL, Ant, X3D, OWL, etc) in ways that Java and Python aren't. The World Wide Web Consortium recently announced its Architecture of the World Wide Web, First Edition. The References section reads like a punch list of technologies that Groovy could kick azz at.



    Thanks! :)


    > Give Groovy continuations and tight XSL integration by embedding Groovy into Cocoon, and there's an unbeatable work flow engine for silly things such as BPEL or a reliable client. I can't think of a better GUI architecture than an XML document player with inlined Groovy scriptlets. Can you?


    :)

    FWIW I'm very interested in having an open sourced Java based (rather than Groovy based) continuations engine. We could put continuations into Groovy but it'd be bit of a hack as the minute you call some Java you loose the ability to do continuations.

    Currently it seems the folks from Rife and some folks interested in maintaining Brakes might end up joining myself and some other codehaus folks and creating a new Java based continuations engine.

    James
    Core Developers Network
  41. I can't think of a better GUI architecture than an XML document player with

    > inlined Groovy scriptlets. Can you?

      Good point. I've already put Groovy support on the Luxor XUL Toolkit todo list. Currently I'm little hold back by the switch over from the Swing UI toolkit to Eclipse. Expect a first Groovy prototype sometime in spring.

      - Gerald
  42. Groovy, Jython, and JSR 223[ Go to top ]

    There is a nice irony if you go to the Groovy Wiki - look at the bottom of the page and it says Python Powered!



    Absolutely. Though don't be surprised if we switch to using SnipSnap the Java (& maybe soon Groovy) based wiki engine :). We've already started using SnipSnap's wiki renderer engine for documentation of the Maven generated website.

    The aim is to unify the Maven documentation and the wiki to be the same set of documentation, all stored in CVS so that we can build the website & generate releases based on the same documentation - then folks can read & edit the docs offline & we can include a PDF of all the documentation with each release. Then the wiki markup can be used in javadocs in java/groovy code. Plus all the documentation should be unit tested, to ensure that any sample code actually works.



    > Now just how long will it take for the Groovy community to start building the types of infrastructure that made Python what it is: the libraries, Mailman, Zope, and Plone???

    The Groovy community is just part of the Java community - its not trying to make a new community per se, just allow Java developers to use some of the expressiveness and power of Python & Ruby inside their platform.

    There's already heaps of Java code out there for many things that Python does; though I'm ducking any kind of platform wars here :). Use the right tool for the job, whatever right means to you based on your circumstances.

    I've heard many good things said about Zope & Plone - I'd be interested to hear if anyone has ever built a comparable things for Java.

    James
    Core Developers Network
  43. Why does Jython go?[ Go to top ]

    I guess there goes Jython.

    >
    > Totally. I think the Java Language Specification is also made obsolete by Groovy. If Groovy runs on Kaffe, then we don't need Sun anymore.

    Disagree. Jython is based on Python having all their libraries available. Additionally Python is a consistent language instead of being a mix of Java and a dozen scripting languages.

    If Jython manages to stay closer to the original Python versions than it does now, I think that Jython will be interesting even for a lot of CPython programmers.

    My hint for Groovy: Document the language and clean up the syntax and semantics. For example: Why does using closure ensures a try-finally-block on file operations. Are there simílar features on iterations that just had not been mentioned or is closure support dependent on the object used for. Anoher one: Are closures taken from functional programming, being a multicommand lambda operator, or are they just unnamed functions, meaning they can produce side effects like some examples suggest.

    Such inconsistencies on a core feature of a language makes it nearly unusable, therefore I wish you a lot of good luck for your project but will continue using Jython for productive scripting tasks.
  44. Why does Jython go?[ Go to top ]

    I guess there goes Jython.

    > >
    > > Totally. I think the Java Language Specification is also made obsolete by Groovy. If Groovy runs on Kaffe, then we don't need Sun anymore.
    >
    > Disagree. Jython is based on Python having all their libraries available. Additionally Python is a consistent language instead of being a mix of Java and a dozen scripting languages.
    >
    > If Jython manages to stay closer to the original Python versions than it does now, I think that Jython will be interesting even for a lot of CPython programmers.


    Agreed. I don't see Jython disappearing any time soon

     
    > My hint for Groovy: Document the language and clean up the syntax and semantics.


    Absolutely. The main focus before the full 1.0 release is gonna be documentation (which hopefully the documentation is also going to be unit tested so all the example code actually works)


    > For example: Why does using closure ensures a try-finally-block on file operations.


    I don't follow. We support this

    file = new File("foo.txt")
    file.eachLine { line | println("received line ${line}") }


    where the eachLine() method handles the opening & closing of the file, ensuring if an exception occurs, the stream is closed. Does that help explain things?

    The try-finally block has nothing to do with the closure per-se, its the eachLine method on the File object.



    > Are there simílar features on iterations that just had not been mentioned or is closure support dependent on the object used for.


    Again I'm not quite sure what you mean. Closures are just a regular Java object which can be passed around & used by any Groovy or Java code.

    http://groovy.codehaus.org/apidocs/groovy/lang/Closure.html


    > Anoher one: Are closures taken from functional programming, being a
    > multicommand lambda operator, or are they just unnamed functions, meaning they can produce side effects like some examples suggest.

    If it helps - closures in Groovy are modeled exactly on Ruby 2.0 closures (which are similar to Smalltalk/Dylan closures).

    They are objects, can be passed around, maintain state and can be used as unnamed functions.

    e.g.

    count = 0
    [1, 2, 3, 4].each { count += it; last = it }
    println("the sum is ${count} and the last item was ${last}")



    > Such inconsistencies on a core feature of a language makes it nearly unusable, therefore I wish you a lot of good luck for your project but will continue using Jython for productive scripting tasks.

    Whilst I'm totally happy for you to continue to use whatever tool you prefer, I'd really appreciate knowing of any language inconsistencies you find.

    James
    Core Developers Network
  45. Why does Jython go?[ Go to top ]

    For example: Why does using closure ensures a try-finally-block on file operations.

    >
    >
    > I don't follow. We support this
    >
    > file = new File("foo.txt")
    > file.eachLine { line | println("received line ${line}") }
    > [...]
    > The try-finally block has nothing to do with the closure per-se, its the eachLine method on the File object.
    >
    This one is taken from http://wiki.codehaus.org/groovy/BlocksAndClosures (The Feature Page)

    to automatically close resources using try/catch/finally type logic

    FileInputStream('foo.txt').using { in |
      while (true) {
        line = in.readLine()
        if (line == null) break
        print line
      }
    }
    // stream will always be closed

    So please tell me why the stream will always be closed with this closure.

    > > Anoher one: Are closures taken from functional programming, being a
    > > multicommand lambda operator, or are they just unnamed functions, meaning they can produce side effects like some examples suggest.
    >
    > If it helps - closures in Groovy are modeled exactly on Ruby 2.0 closures (which are similar to Smalltalk/Dylan closures).
    >
    > They are objects, can be passed around, maintain state and can be used as unnamed functions.
    >
    > e.g.
    >
    > count = 0
    > [1, 2, 3, 4].each { count += it; last = it }
    > println("the sum is ${count} and the last item was ${last}")
    These examples (taken from the same page as above) look completely different:
    result1 = list.find { i | return i != 'b' }
    result2 = foo.find { key, value | return key != 'blah' }
    They look and function a bit like lambda-functions in python. The example you gave is rather strange, i.e. what the hell is "it". Well, I can figure it means some type of iterator, but what if I passed this closure to a File object, for example. Thinks like debugging will be interesting in such a case...

    > Whilst I'm totally happy for you to continue to use whatever tool you prefer, I'd really appreciate knowing of any language inconsistencies you find.
    One I already described above. Next one is from http://wiki.codehaus.org/groovy/CoreSyntax

    class Foo
     
      def blah(a, b) {
            return a * b;
      }

    The first line looks like class definition is done by indenting like in Python, but the method is defined with curly braces.
    Perhaps that's only an inconsistency in documentation, but topics like the core syntax are rather important, so at least the documentation is not consistent. Thus I think that Groovy is interesting, but not production ready yet, what I expect of an 1.0 release.

      -Markus
  46. Why does Jython go?[ Go to top ]

    Perhaps that's only an inconsistency in documentation, but topics like the core syntax are rather important, so at least the documentation is not consistent. Thus I think that Groovy is interesting, but not production ready yet, what I expect of an 1.0 release.

    >
    >   -Markus

    I agree. Python has a lot of PEPs(Python Enhancement Proposals)http://www.python.org/peps/ which document the discussion of every new feature proposed whether it will finally be accepted into offical release or not and why. I do hope Groovy will accelerate the java development to a higer level of productivity, cause it takes so many strongpoints from python,ruby and smalltalk while kept seamless to java in mind. However, there's a need of time to demonstrate the consistency of so many features in one language.
  47. Why does Jython go?[ Go to top ]

    For example: Why does using closure ensures a try-finally-block on file operations.

    > >
    > >
    > > I don't follow. We support this
    > >
    > > file = new File("foo.txt")
    > > file.eachLine { line | println("received line ${line}") }
    > > [...]
    > > The try-finally block has nothing to do with the closure per-se, its the eachLine method on the File object.
    > >
    > This one is taken from http://wiki.codehaus.org/groovy/BlocksAndClosures (The Feature Page)
    >
    > to automatically close resources using try/catch/finally type logic
    >
    > FileInputStream('foo.txt').using { in |
    >   while (true) {
    >     line = in.readLine()
    >     if (line == null) break
    >     print line
    >   }
    > }
    > // stream will always be closed
    >
    > So please tell me why the stream will always be closed with this closure.


    Its not the closure doing the closing of the stream. The above example, the 'using' is a method call which takes a closure. The using() method would handle the closing of the stream.

    So its equivalent to this...

    c = { in | .... }
    FileInputStream("foo.txt").using(c)

    maybe just having a single helper method would be neater & more clear

    FileInputStream("foo.txt", c)

    BTW that wiki page was reverted to an old version by a robot - hit refresh and you should be much more up to date. This was just an example to show how closures could be used to simplify exception handling in once place, rather than littering application code with this stuff.



    > > > Anoher one: Are closures taken from functional programming, being a
    > > > multicommand lambda operator, or are they just unnamed functions, meaning they can produce side effects like some examples suggest.
    > >
    > > If it helps - closures in Groovy are modeled exactly on Ruby 2.0 closures (which are similar to Smalltalk/Dylan closures).
    > >
    > > They are objects, can be passed around, maintain state and can be used as unnamed functions.
    > >
    > > e.g.
    > >
    > > count = 0
    > > [1, 2, 3, 4].each { count += it; last = it }
    > > println("the sum is ${count} and the last item was ${last}")
    > These examples (taken from the same page as above) look completely different:
    > result1 = list.find { i | return i != 'b' }


    BTW the 'return' statement is optional in Groovy, rather like Ruby.

    Unfortunately some of the Wiki was out of date - we had a robot reverting stuff back to old versions. Its now been fixed AFAIK. Humble apologies for the confusion.

    FWIW the more up to date documentation of closures is here

    http://groovy.codehaus.org/closures.html

    and here

    http://groovy.codehaus.org/quickStart.html


    > result2 = foo.find { key, value | return key != 'blah' }
    > They look and function a bit like lambda-functions in python. The example you gave is rather strange, i.e. what the hell is "it".


    Again sorry for our lousy documentation. We're working hard on fixing that.

    Basically with closures in Groovy you can name the parameters like lambda-functions in python or closures in Ruby, Dylan & Smalltalk.

    closure = { a, b, c | println( a + b + c) }

    You can also statically type them too if you want...

    closure2 = { String a, Integer y | println(a * y) }

    If you want to you can omit the parameter declaration and one default parameter, called 'it' becomes available. This is an idea borrowed from Xen which makes doing XPath style navigation much more concise. Its totally up to you as the developer whether you want to name your parameters or just use the default 'it' parameter.

    closure3 = { println("I was passed ${it}") }


    > Well, I can figure it means some type of iterator, but what if I passed this closure to a File object, for example. Thinks like debugging will be interesting in such a case...


    Parameters into a closure can be any object. e.g. the Groovy SQL helper class passes in either a ResultSet or a bean representing the row...

    http://groovy.codehaus.org/sql.html


    The above is also a neat example of writing exception handling once (of result set, statement and connnection) and then just reusing the exception handling with closures in application developer code.



    > > Whilst I'm totally happy for you to continue to use whatever tool you prefer, I'd really appreciate knowing of any language inconsistencies you find.
    > One I already described above. Next one is from http://wiki.codehaus.org/groovy/CoreSyntax
    >
    > class Foo
    >  
    >   def blah(a, b) {
    >         return a * b;
    >   }
    >
    > The first line looks like class definition is done by indenting like in Python, but the method is defined with curly braces.


    Again this is now fixed. This was really old wiki cruft I'm afraid due to the robot reverting the wiki content. Sorry for the confusion - if you do a refresh it should be neater now.


    > Perhaps that's only an inconsistency in documentation, but topics like the core syntax are rather important, so at least the documentation is not consistent. Thus I think that Groovy is interesting, but not production ready yet, what I expect of an 1.0 release.


    You're right the documentation needs work. Though remember this is the first ever beta release of Groovy. We'll have way better documentation by the time the full 1.0 release is out. Some of the confusion has been caused by some wiki pages being reverted back to old versions.

    Thanks for your comments.

    James
    Core Developers Network
  48. Haven't I seen this like 3 years ago[ Go to top ]

    Looks like you boys have re-created Anvil (http://njet.org/), which has all the features you just listed and more, and the syntax seems also suprisingly same =)