Rao
Rao

Reputation: 21369

Multiple assignments using with() in Groovy

Seen good working examples in groovy using with.

Question: However, having trouble or could not understand the reason for not giving desired output when using it with the combination of keyword this.with{..} as shown below:

Here is the code for Person.groovy

class Person {

    def name
    def address
    def mail

    Person(name, address, mail){
        this.with {
            name = name
            address = address
            mail = mail
        }
    }

    String toString() {
        "${name} ${address} ${mail}"
    }
}

When you call the above class with below code, output is coming as null null null instead of abc xyz [email protected]

def person1 = new Person('abc', 'xyz', '[email protected]')
println person1.toString()

Upvotes: 1

Views: 325

Answers (2)

Will
Will

Reputation: 14529

Groovy can't resolve the same identifier to two different elements. You could try with the setX instead:

class Person {
    def name
    def address
    def mail

    Person(name, address, mail){
        setName name
        setAddress address
        setMail mail
    }

    String toString() { "$name $address $mail" }
}

assert new Person('abc', 'xyz', '[email protected]').toString() ==
    'abc xyz [email protected]'

Upvotes: 2

Opal
Opal

Reputation: 84786

It should be:

class Person {

    def name
    def address
    def mail

    Person(name, address, mail){
        with {
            this.name = name
            this.address = address
            this.mail = mail
        }
    }

    String toString() {
        "${name} ${address} ${mail}"
    }
}

def person1 = new Person('abc', 'xyz', '[email protected]')
println person1.toString()

Since groovy doesn't know how to distinguish name from object from name argument passed to constructor.

You can also try:

Person(namea, addressa, maila){
    with {
        name = namea
        address = addressa
        mail = maila
    }
}

If you change the variables names (I mean class fields will be called differently than constructor args) you don't with nor this.

Upvotes: 2

Related Questions