英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论