Shorthand way for assigning object properties in Groovy?

后端 未结 3 1514
轻奢々
轻奢々 2021-02-12 16:09

I create Groovy objects using this convention...

Item item1 = new Item( name: \"foo\", weight: \"150\")

...is there a shorthand convention for

3条回答
  •  后悔当初
    2021-02-12 16:59

    I prefer item1.with if I have concrete variables to change

    item1.with {
        name = "lalal"
        weight = 86
        high = 100
    }
    

    I prefer InvokerHelper.setProperties when I have map of properties (can be any size)

    @ToString
    class Item{
        def name
        def weight
    }
    Item item1 = new Item( name: "foo", weight: "150")
    
    println "before: $item1"
    use(InvokerHelper) {
        item1.setProperties weight: 22, name: "abc"
    }
    println "after : $item1"
    

    Output:

    before: Item(foo, 150)
    after : Item(abc, 22)
    

提交回复
热议问题