Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

...

Code Block
languagegroovy
interface Predicate {
   boolean    boolean test(obj)
}

List filter(List list, Predicate pred) {
   list    list.findAll { pred.test(it) }
}

def input = [1, 2, 3, 4, 5]

def odd = filter(input) { it % 2 == 1 }
assert odd == [1, 3, 5]

...

Code Block
languagegroovy
import groovy.transform.Memoized

@Memoized int expensiveOp(int a, int b) {
   sleep    sleep 1000
   return    return a + b
}
// one second to return
expensiveOp(1, 2)

// immediate result returned

expensiveOp(1, 2)

...

Code Block
languagegroovy
// import the CompilerConfiguration class
// to configure the base script class
import org.codehaus.groovy.control.CompilerConfiguration

// the script we want to compile
def scriptContent = '''
   name    name = "Guillaume"
   sayHi    sayHi()
'''

// the class definition of the delegate
class Person {
   String    String name
   void    void sayHi() {
       println         println "Hi $name"
       }
}

// configure the base script class
def cc = new CompilerConfiguration()
cc.scriptBaseClass = DelegatingScript.class.name

// parse script with GroovyShell
// and the configuration
def sh = new GroovyShell(cc)
def script = sh.parse(scriptContent)

// set the delegate and run the script
def p = new Person()
script.setDelegate(p)
script.run()

// the name is set correctly
// and the output will display "Hi Guillaume"
assert p.name == "Guillaume"

...

Code Block
languagegroovy
import groovy.transform.*

@InheritConstructors
class MyList extends LinkedList<String> {}

public <T> Object map(
     @DelegatesTo        @DelegatesTo.Target List<T> target,
     @DelegatesTo        @DelegatesTo(genericTypeIndex = 0) Closure arg) {
   arg    arg.delegate = target.join('')
   arg    arg()
}

@TypeChecked
def test() {
   map    map(new MyList(['f', 'o', 'o'])) {
       assert         assert toUpperCase() == 'FOO'
       }
} 

Note the genericTypeIndex attribute of @DelegatesTo that points at the index of the generic component. Unfortunately, as the generic placeholders are not kept at the bytecode level, it’s impossible to just reference T, and we had to use an index to point at the right type.

...