使用 Elvis/三元运算符作为函数参数

huangapple go评论43阅读模式
英文:

Using elvis/ternary operator as an argument to a function

问题

让我们假设我在Groovy中有这段代码:

String x
String y = "hello"

def func(String str){
   println(str)
}

func(x ?: y)

像我上面那样在函数参数中使用Elvis运算符有什么问题吗?我测试过,它按预期工作,但是我从未见过Elvis运算符被传递到函数中。

提前感谢!

英文:

Let's say I have this block of code in Groovy:

String x
String y = "hello"

def func(String str){
   println(str)
}

func(x ?: y)

Is there anything wrong with using Elvis operator as an argument to a function like I did above? I tested it and it works as expected, however, I've never seen Elvis operator to be passed to a function like that.

Thanks in advance!

答案1

得分: 1

我从未见过将Elvis运算符传递给函数。与您的直觉相反,您在这里也没有看到它。运算符并未传递给函数。而是传递了表达式的结果。

这个表达式评估为一个结果:

x ?: y

这个表达式的结果是一个String值。该String值被传递给函数。函数不关心在传递给函数之前如何生成该String值。

英文:

> I've never seen Elvis operator to be passed to a function

Contrary to what your intuition is telling you, you're not seeing it here either. The operator isn't passed to the function. The result of the expression is.

This expression evaluates to a result:

x ?: y

The result of this expression is a String value. That String value is passed to the function. It doesn't matter to the function how that String value was produced before it was passed to the function.

huangapple
  • 本文由 发表于 2023年7月14日 04:42:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76683114.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定