Java调用方法和使用三元运算符并在参数中赋值? [英] Java calling method and using ternary operator and assign in the parameters?
问题描述
我正在查看一些代码,并且遇到了这个问题:
I was reviewing some code and I came across this:
public static doSomething(String myString, String myString2) {
//Stuff
}
public static doAnotherThing(String myString) {
return doSomething(myString = myString != null ? myString.toLowerCase(): myString, null)
}
这是如何工作的?,我知道将.toLowerCase结果字符串分配给myString(是的,我知道这是不好的作法,因为实际上您不应该重新分配方法参数,因为它们应该是最终的),但是我不太确定该方法如何始终接收所需的2个参数.
How is this working exactly?, I know the .toLowerCase resulting string is assigned to myString (yes I know bad practice since you are not supposed to reassign method parameters in fact they should be final), but I am not quite sure how does the method always receives the 2 parameters it needs.
我知道myString为null或至少我认为是如何工作的,因为三元数有myString为null,但是我不确定为什么myString不为null时为什么会去那里.
I know how it works when myString is null or at least I think I do, since the ternary has myString, null, but I am not quite sure why it would go there when myString is not null?.
推荐答案
救援的感觉!
doSomething(myString = ( ( myString != null ) ? myString.toLowerCase() : myString ), null)
要了解这一点,您需要了解两件事:
To understand this, you need to know two things:
- 三元运算符的工作原理
- 赋值运算符返回它所赋值的事实
这篇关于Java调用方法和使用三元运算符并在参数中赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!