Abe
Abe

Reputation: 9031

groovy "with" block usage query

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

Upvotes: 10

Views: 10086

Answers (2)

tim_yates
tim_yates

Reputation: 171154

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

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

Upvotes: 19

winstaan74
winstaan74

Reputation: 1131

It's hard to see what the problem is without seeing the definition of your class. I'll assume that TxId and oapTxId are both properties of the class.

I suspect your error is caused by oapTxId being of type MyXMLTemplate, and so not assignable from String.

Incidetally, as your with block is just initializing class properties, you could use the more idiomatic constructor and setters approach:

MyXmlTemplate template = new MyXMLTemplate(TxId: 'mnop', oapTxId : 'abcd')

Upvotes: 3

Related Questions