我有3个如下所示的变量,我希望结果的优先级为return x,如果x为空则返回y,如果x和y都为空则返回z。
下面是我的代码,但这不起作用。
val x = "1"
val y = "2"
val z = "3"
val result = {
var res = "
if (x == "") y else x
else if (y == "") z
}
For result First priority is to x and if x = "" then y, if y also "" then return z
请帮助
答案 0 :(得分:0)
您正在将Integer值分配给变量并检查条件是否为空字符串。 Comparing values of types Int and String using `==' will always yield false
请检查以下代码。
// For variables of type string.
if(x != "") x else if (y != "") y else z
scala> val x = 1
x: Int = 1
scala> val y = 2
y: Int = 2
scala> val z = 3
z: Int = 3
scala> if(x != "") x else if (y != "") y else z // This will give result if variables are type string. but if it is int type checking this way give you wrong values.
<console>:30: warning: comparing values of types Int and String using `!=' will always yield true
if(x != "") x else if (y != "") y else z
^
<console>:30: warning: comparing values of types Int and String using `!=' will always yield true
if(x != "") x else if (y != "") y else z
^
res8: Int = 1
scala> if (!x.isNaN) x else if(!y.isNaN) y else z // Check this way