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?
Use the
withmethod call on your last example: