【问题标题】:Comparing Strings in Scala - equals vs ==比较 Scala 中的字符串 - 等于 vs ==
【发布时间】:2017-11-23 12:05:36
【问题描述】:

我正在尝试比较 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"
     | }

来自some answers 我假设我可以使用“==”符号来比较字符串。我给出了以下输入并得到了以下输出。我错过了什么或 Scala 的行为有所不同?

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

println(max(2, "sam"))
This is greater than 1

【问题讨论】:

  • 我认为问题不在于==,而在于您有两个 if/else.stackoverflow.com/a/12560532/3072566
  • 谢谢@litelite。我会保留这个问题以供其他人参考。
  • @Dinesh,请接受答案。

标签: scala string-comparison


【解决方案1】:

这是因为在 scala 中最后一个可达语句的值是函数的结果。在这种情况下,对于 "max (1,"Happy")",代码将进入 y="happy" 但之后它会进入 if(x>1) 的 else 分支。由于这是函数中的最后一条语句,因此您将得到它作为结果。

为了交叉检查它在第一个 if 块中引入一个 print 语句

 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,"Happy")" 调用

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

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

【讨论】:

    【解决方案2】:

    您的 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)
    

    希望这个回答对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-08
      • 1970-01-01
      • 2010-12-25
      • 2012-08-22
      • 2014-12-05
      • 2011-02-28
      相关资源
      最近更新 更多