比较 Scala 中的字符串 - 等于 vs ==



我正在尝试比较 Scala 中的两个字符串。下面是函数。

def max(x:Int, y:String): String = {
     | if (y=="Happy") "This is comparing strings as well"
     | else "This is not so fair"
     | if (x > 1) "This is greater than 1"
     | else "This is not greater than 1"
     | }

从一些答案中,我假设我可以使用"=="符号来比较字符串。我给出了以下输入并得到了以下输出。我错过了什么,或者 Scala 的行为有所不同?

max (1,"Happy")
res7: String = This is not greater than 1
println(max(2, "sam"))
This is greater than 1

发生这种情况是因为在 scala 中,最后一个可访问语句的值是函数结果。在这种情况下,对于"max (1,"Happy"(",代码进入 y="happy",但紧接着它进入 if(x>1( 的 else 分支。由于这是函数内的最后一个语句,因此您得到它作为结果。

要交叉检查它,请在第一个 if 块中引入打印语句

 def max(x:Int, y:String): String = {
     | if (y=="Happy") println("This is comparing strings as well")
     |  else "This is not so fair"
     | if (x > 1) "This is greater than 1"
     | else "This is not greater than 1"
     | }

现在使用"max(1,"快乐"("呼叫

结果:这也是比较字符串这不大于 1

这表明您正在以正确的方式比较字符串。

您的max函数只返回一个字符串,并且该字符串始终是最后一个if else语句。如果你想要两个比较输出,那么你应该返回一tuple2字符串

作为
scala>     def max(x:Int, y:String): (String, String) = {
     |       var string1 =  "This is not greater than 1"
     |       var string2 = "This is not so fair"
     |       if (x > 1) string1 = "This is greater than 1"
     |       if (y=="Happy") string2 = "This is comparing strings as well"
     |       (string1, string2)
     |     }
max: (x: Int, y: String)(String, String)
scala> max(1, "Happy")
res0: (String, String) = (This is not greater than 1,This is comparing strings as well)
scala> res0._1
res1: String = This is not greater than 1
scala> res0._2
res2: String = This is comparing strings as well
scala> max(2, "sam")
res3: (String, String) = (This is greater than 1,This is not so fair)

我希望这个答案有所帮助

最新更新