Hidden features of Groovy?

It seems like Groovy was forgotten in this thread so I'll just ask the same question for Groovy.

  • Try to limit answers to Groovy core
  • One feature per answer
  • Give an example and short description of the feature, not just a link to documentation
  • Label the feature using bold title as the first line
  • See also:

  • Hidden features of Python
  • Hidden features of Ruby
  • Hidden features of Perl
  • Hidden features of Java

  • Using the spread-dot operator

    def animals = ['ant', 'buffalo', 'canary', 'dog']
    assert animals.size() == 4
    assert animals*.size() == [3, 7, 6, 3]
    

    This is a shortcut for animals.collect { it.size() } .


    The with method allows to turn this:

     myObj1.setValue(10)
     otherObj.setTitle(myObj1.getName())
     myObj1.setMode(Obj1.MODE_NORMAL)
    

    into this

     myObj1.with {
        value = 10
        otherObj.title = name
        mode = MODE_NORMAL
     }
    

    Using hashes as pseudo-objects.

    def x = [foo:1, bar:{-> println "Hello, world!"}]
    x.foo
    x.bar()
    

    Combined with duck typing, you can go a long way with this approach. Don't even need to whip out the "as" operator.

    链接地址: http://www.djcxy.com/p/42816.html

    上一篇: 你最喜欢的LINQ to Objects运算符是不是构建的

    下一篇: Groovy的隐藏功能?