埃尔维斯操作符是三元运算符的缩写形式。使用这种便捷写法的一个实际场景是:如果一个表达式求值为假(基于 Groovy 真值)时需要返回一个合理的默认值的情况。

displayName = user.name ? user.name : 'Anonymous'    //1
displayName = user.name ?: 'Anonymous'    //2

 

//1: 使用三元操作符时,你必须重复你想要赋值的那个值
//2: 使用埃尔维斯操作符时,如果被测试值为真时,就会使用该值作为返回值
使用埃尔维斯操作符能够降低代码的复杂性也能够减小代码重构时发生错误的几率:因为不需要在条件和真值返回值部分重复被测试的表达式。

 

 

https://blog.csdn.net/qq_26886929/article/details/86601589

相关文章:

  • 2021-11-14
  • 2022-12-23
  • 2022-12-23
  • 2022-01-13
  • 2022-12-23
  • 2021-09-07
  • 2021-09-27
猜你喜欢
  • 2021-07-03
  • 2021-08-11
  • 2021-05-20
  • 2022-12-23
  • 2021-12-03
  • 2022-01-22
  • 2022-12-23
相关资源
相似解决方案