如果属性不为空,我正在使用 Grails 在域类上设置属性。目前,代码如下所示:
def product = Product.getById(5);
if (!product.Name) {
product.Name = "Default Product"
}
if (!product.Price) {
product.Price = 5;
}
if (!product.Type) {
product.Type = "Shampoo"
}
在 Groovy 中实现此代码块的更好方法是什么?我设法将其简化为:
product.Name = product.Name ?: "Default Product"
product.Price = product.Price ?: 5
product.Type = product.Type = "Shampoo"
但我希望能够做这样的事情(无效代码):
product {
Name = product.Name ?: "Default Product",
Price = product.Price ?: 5,
Type = product.Type ?: "Shampoo"
}
你们会建议我做什么?