Groovy magic: asType

Every one who used Grails had to deal (or will have) with XML/JSON converters. They allow to transform object by using syntax like:

 
import grails.converters.*
 
class TestController {
    def index = {
         [a:1, b:2, c:3] as JSON
    }
}
 

I like this "as" syntax, is very verbose and clear. How we can implement in our code? Simple, just use asType method:

 
class Foo {
    def name
 
    String toString(){
        "Foo name is ${name}"
    }
}
 
class Bar {
    def name
 
    String toString(){
        "Bar name is ${name}"
    }
}
 
class Bas {
 
    def name
 
    String toString(){
        "Bas name is ${name}"
    }
 
    Object asType(Class type){
        typeWorker[type](this)
    }
 
    @Lazy
    private def typeWorker = [(Foo):asFoo, (Bar):asBar]
 
    private def asFoo = {it ->
        new Foo(name:it.name)
    }
 
    private def asBar = {it ->
        new Bar(name:it.name)
    }
}
 
def bas = new Bas(name:"Gringo")
 
println bas
println bas as Foo
println bas as Bar
 

and output will be :

Bas name is Gringo
Foo name is Gringo
Bar name is Gringo

Powered by WordPress with GimpStyle Theme design by Horacio Bella.
Entries and comments feeds. Valid XHTML and CSS.