Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

groovy "with" block usage query

Tags:

groovy

I am trying to use the with block in Groovy to easily initalize my class, but I am getting the following error. Could anyone tell me what I am doing wrong?

MyXMLTemplate template = new MyXMLTemplate ().with {
    TxId = 'mnop'
    oapTxId = 'abcd'
}

The error I get is:

org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'abcd' with class 'java.lang.String' to class 'org.example.MyXMLTemplate'
at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.castToType(DefaultTypeTransformation.java:331)
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.castToType(ScriptBytecodeAdapter.java:599)

I am using groovy 1.8.0

like image 234
Abe Avatar asked Sep 08 '11 07:09

Abe


1 Answers

You need to return the template itself from the with block:

MyXMLTemplate template = new MyXMLTemplate ().with {
    TxId = 'mnop'
    oapTxId = 'abcd'
    it
}
like image 98
tim_yates Avatar answered Oct 20 '22 17:10

tim_yates