如何在if else中匹配多个条件

问题描述 投票:0回答:1

我有3个像下面这样的变量,我想让结果优先返回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

请帮助我

scala apache-spark if-statement
1个回答
0
投票

你是在给变量分配整数值& 如果有条件,则检查空字符串。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

© www.soinside.com 2019 - 2024. All rights reserved.