问号在GSP/Grails中意味着什么?

Ami*_*far 41 grails groovy operators gsp

我在生成的GSP页面中看到了这一点.那是什么意思?

<g:textField name="name" value="${phoneInstance?.name}" />
Run Code Online (Sandbox Code Playgroud)

Bur*_*ith 62

它是"安全导航操作符",它是一个Groovy功能,可以简洁地避免空指针异常.见http://docs.groovy-lang.org/latest/html/documentation/index.html#_safe_navigation_operator

在这种情况下,如果phoneInstance为null,则它不会尝试获取name属性并导致NPE - 它只是将字段标记的值设置为null.

  • 为了获得额外的酷感,您还可以使用Elvis操作符添加合理的默认值,例如:`$ {phoneInstance?.number?:'+ 44'}`摇滚时尚与国王宝贝! (11认同)