开发者

Is it possible to override List accessors in Grails domain classes?

开发者 https://www.devze.com 2022-12-24 12:01 出处:网络
If I have a List in a Grails domain class, is there a way to override the addX() and removeX() accessors to it?

If I have a List in a Grails domain class, is there a way to override the addX() and removeX() accessors to it?

In the following example, I'd expect MyObject.addThing(String) to be called twice. In fact, the output is:

Ad开发者_如何学JAVAding thing: thing 2

class MyObject {
    static hasMany = [things: String]
    List things = []

    void addThing(String newThing) {
        println "Adding thing: ${newThing}"
        things << newThing
    }
}

class BootStrap {
    def init = { servletContext ->
            MyObject o = new MyObject().save()
            o.things << 'thing 1'
            o.addThing('thing 2')
        }
        def destroy = {
    }
}


The method should be called leftShift(String), not addThing(), as documented on the Groovy operator overloading page.


Moving my comment to an answer:

Try using the built-in addToThings as documented here:

http://www.grails.org/doc/latest/ref/Domain%20Classes/addTo.html


I don't understand why you expect addThing() to be called twice? Here's an explanation of your code

// things is a List, so this calls List.leftShift(Object) 
o.things << 'thing 1'

// o is an instance of MyObject, so this calls addThing()
o.addThing('thing 2')

So you're only calling addThing() once.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号