How do I simplify this code in Groovy that sets properties on an object if they are null?

grails, groovy

Solution

Use the `with` method call on your last example:

product.with {
    Name = Name ?: "Default Produce"
    Price = Price ?: 5
    Type = Type ?: "Shampoo"
}

Problem

I'm using Grails to set properties on a domain class if the property is not null. Currently, the code looks something like this: ``` def product = Product.getById(5); if (!product.Name) { product.Name = "Default Product" } if (!product.Price) { product.Price = 5; } if (!product.Type) { product.Type = "Shampoo" } ``` What is a better way of implementing this code block in Groovy? I managed to simplify it to: ``` product.Name = product.Name ?: "Default Product" product.Price = product.Price ?: 5 product.Type = product.Type = "Shampoo" ``` But I'd like to be able to do something like this (not valid code): ``` product { Name = product.Name ?: "Default Product", Price = product.Price ?: 5, Type = product.Type ?: "Shampoo" } ``` What would you guys recommend I do?

Original source