Writing sentences with Groovy 2.0

22 / Mar / 2012 by Vivek Krishna 1 comments

Groovy 2.0 comes with some amazing new features, which prompted a numbering scheme jump from 1.9.x to 2.0. One of the key features that I took note while going through  Guillaume Laforge’s presentation at 33rd Degree was the support for plain language sentences made possible by optional parentheses,  and dots.

We love the language and we love pizza! So, I put together a small script to demonstrate the power of natural language support available on Groovy 2.0 (Tested the feature on 2.0.0-beta2).

The PizzaDelivery takes orders and outputs the order.


class PizzaDelivery {

    Integer quantity
    String topping
    Date time

    PizzaDelivery need(Integer quantity){
        this.quantity = quantity
        return this
    }

    PizzaDelivery with(String topping){
        this.topping = topping
        return this
    }

    PizzaDelivery at(String time) {
        this.time = Date.parse('h:mm', time)
        return this
   }

   String toString(){
        return "${quantity} ${topping} at ${time.format('h:mm')} hours"
   }
}

PizzaDelivery pizzaDelivery = new PizzaDelivery()
pizzaDelivery.with{
    need 3 with 'pepperoni' at '6:00'           // need(3).with('pepperoni').at("6:00")
}

println pizzaDelivery

This will allow us to create very simple yet elegant DSLs which would feel like English or any other language that one feels comfortable with.

FOUND THIS USEFUL? SHARE IT

comments (1 “Writing sentences with Groovy 2.0”)

  1. ugg boots clearance

    wanne buy to buy UGG Classic Short Boots 5831 Check Chocolate clearance ,it`s UGG Classic Short Boots 5831 Check Chocolate Color:Chocolate Boot shaft height: 9.4 ” Heel height: 1.25 This boot is extremely comfortable, made with the finest Twin-face sheepskin Classic collection, which is famous for its molded insole covered by natural wool With fur and metal rivets in each shoeThis style has to be specially made for 3-5 working days. at cheap uggs.

    Reply

Leave a comment -