Reputation: 38430
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?
Upvotes: 3
Views: 156
Reputation: 19229
Not sure if simpler, but maybe more re-usable:
def setDefaults(obj, Map defaults) {
defaults.each { k, v -> obj[k] = obj[k] ?: v }
}
setDefaults(product, [Name: 'Default Product', Price: 5, Type: 'Shampoo'])
Upvotes: 0
Reputation: 3881
Use the with
method call on your last example:
product.with {
Name = Name ?: "Default Produce"
Price = Price ?: 5
Type = Type ?: "Shampoo"
}
Upvotes: 5