Christoph Hartmann on September 11th, 2008

Java Iteration Example

import java.util.Date;
 
public class Foo {
    public static void main(String[] args) {
        int start = 1;
        int summe = 0;
 
        for (int i = start; i <= 5; i++) {
            summe += i;
        }
 
        Date now = new Date();
        System.out.println(now.toString() + " Die Summe ist: " + summe);
    }
}

Groovy Iteration Example within Groovy Shell

 
        start = 1
        summe = 0
 
        for (i in start..5) {
            summe += i
        }
 
        now = new Date()
        println "$now Die Summe ist: $summe"

Groovy Map Handling with Closures

map = ["a":1, "b":2]
 
// inline closure
map.each { key, value ->
    map[key] = value*2
}
println map
 
// extern closure
doubler = { key, value ->
    map[key] = value*2
}
map.each(doubler)
println map

Groovy Beans

class Book {
    String title
 
    Book (String theTitle) {
        title = theTitle
    }
    Book plus(Book anotherBook) {
        return new Book(title + ", " + anotherBook.title)
    }
}
Book gina = new Book("Groovy in Action")
// getters are generated automatically 
println gina.getTitle()
 
println ((gina + new Book("Groovy for Experts")).title)

Groovy Duck Typing

 
class Dog {
    def speak() { println "wuff" }
}
class Cat {
    def speak() { println "miau" }
}
def saySomething(somewhat) {
    somewhat.speak()
}
 
saySomething(new Dog())
saySomething(new Cat())

Simple XML Example:

 
class XmlBuilder {
   def out
   XmlBuilder(out) { this.out = out }
   def invokeMethod(String name, args) {
       out << "<$name>"
       if(args[0] instanceof Closure) {
            args[0].delegate = this
            args[0].call()
       }
       else {
           out << args[0].toString()
       }
       out << "</$name>"
   }
}
 
def xml = new XmlBuilder(new StringBuffer())
xml.html {
    head {
        title "Hello World"
    }
    body {
        p "Welcome!"
    }
}
println xml.out

Tags: , ,

Leave a Reply