【发布时间】:2011-06-02 15:57:01
【问题描述】:
我在生成的 GSP 页面中看到了这一点。 ?是什么意思?
<g:textField name="name" value="${phoneInstance?.name}" />
【问题讨论】:
标签: grails groovy operators gsp
我在生成的 GSP 页面中看到了这一点。 ?是什么意思?
<g:textField name="name" value="${phoneInstance?.name}" />
【问题讨论】:
标签: grails groovy operators gsp
它是“安全导航运算符”,它是一个 Groovy 功能,可以简洁地避免空指针异常。见http://docs.groovy-lang.org/latest/html/documentation/index.html#_safe_navigation_operator
在这种情况下,如果 phoneInstance 为 null,则它不会尝试获取 name 属性并导致 NPE - 它只是将字段标记的值设置为 null。
【讨论】:
${phoneInstance?.number?:'+44'} Rock groovy with the king baby!
? 运算符允许在 Groovy(以及因此,GSP)中使用空值。例如,通常在 gsp 中,
<g:field name="amount" value="${priceDetails.amount}" />
如果priceDetails 为空,则会抛出NullPointerException。
如果我们改用? 运算符...
<g:field name="amount" value="${priceDetails?.amount}" />
现在${priceDetails?.amount} 的值为空,而不是抛出空指针异常。
【讨论】:
这是 Groovy 中非常重要的特性。如果对象为空(即, “phoneInstance”为空)然后它提供“空”值。这项特征 被称为“安全导航操作员”。只要我们使用这个特性,就不需要检查object("phoneInstance")是否为null。
【讨论】:
如果左侧的对象为空,安全导航运算符 (?.) 返回空,否则返回该对象右侧成员的值。所以phoneInstance?.name 只是phoneInstance == null ? null : phoneInstance.name 的简写
例如:
a = x?.y
只是以下的简写:
a = (x == null ? null : x.y)
简写为:
if(x == null){
a = null
} else {
a = x.y
}
【讨论】: