Scala判斷字符串是否相等

在Scala中可以通過==判斷字符串實例是否相等,eg.

scala> val s1 = "Hello"
s1: String = Hello

scala> val s2 = "Hello"
s2: String = Hello

scala> val s3 = "H" + "ello"
s3: String = Hello

scala> val s4 = Array("H", "e", "l", "l", "o").mkString("")  
s4: String = Hello

scala> s1 == s2
res0: Boolean = true

scala> s1 == s3
res1: Boolean = true

scala> s1 == s4
res2: Boolean = true

scala> s2 == s3
res3: Boolean = true

scala> s1.eq
eq   equals   equalsIgnoreCase

scala> s1.equals(s2)
res4: Boolean = true

scala> s1.equals(s3)
res5: Boolean = true

scala> s1.equals(s4)
res6: Boolean = true

scala> s1.eq(s2)
res7: Boolean = true

scala> s1.eq(s3)
res8: Boolean = true

scala> s1.eq(s4)
res9: Boolean = false

在此,特別感謝Z盡際的提醒,增加了val s4 = Array("H", "e", "l", "l", "o").mkString("") 這個例子,s1,s2,s3編譯之后會變成同一個對象的引用,比較字符串相等沒有意義,增加s4更能說明上面的結(jié)論;

==在AnyRef中是一個函數(shù),其定義如下:

/** The expression `x == that` is equivalent to `if (x eq null) that eq null else x.equals(that)`.
   *
   *  @param    arg0  the object to compare against this object for equality.
   *  @return         `true` if the receiver object is equivalent to the argument; `false` otherwise.
   */
  final def ==(that: Any): Boolean =
    if (this eq null) that.asInstanceOf[AnyRef] eq null
    else this equals that

其中if (this eq null) that.asInstanceOf[AnyRef] eq null會判斷當前String對象是否為空,所以null也可以使用==來比較,并且兩個null字符串比較會得到true的結(jié)果也不會拋出NullPointerException; eg.

scala> s4 = null
<console>:11: error: not found: value s4
       s4 = null
       ^
<console>:12: error: not found: value s4
       val $ires0 = s4
                    ^

scala> val s4:String = null
s4: String = null

scala> val s5:String = null
s5: String = null

scala> s4 == s5
res2: Boolean = true

但是,如果使用null字符串做一些函數(shù)操作,則會拋出NullPointerException,eg.

scala> s4.isEmpty
java.lang.NullPointerException
  ... 28 elided

如果要忽略大小寫比較字符串,可以使用java的equalsIgnoreCase方法,eg.

scala> val s6 = "Amgen"
s6: String = Amgen

scala> val s7 = "amgen"
s7: String = amgen

scala> s6 == s7
res4: Boolean = false

scala> s6.equalsIgnoreCase(s7)
res5: Boolean = true

<font color=#0099ff size=7 face="黑體">\033[1q Scala不推薦使用null,可以使用Option代替 </font>

<font color=red>Markdwon測試</font>
"\033[34mdanran\033[0m" danran藍色顯示

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容