Scala学习之字符串篇(一):字符串的比较

在Scala中你只须要使用==就能够判断字符串相等,而不须要像Java同样须要使用的equals方法来判断。java

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

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

scala> val s3 = "h" + "ello"
s3: String = hello

scala> s1 == s2
res4: Boolean = true

scala> s1 == s3
res5: Boolean = true

使用==判断字符串相等的好处是,能够避免空指针异常。即==左边的字符串是空,也能够正常判断。es6

scala> val s4 = null
s4: Null = null

scala> s4 == s3
res6: Boolean = false

scala> s3 == s4
res7: Boolean = false

忽略大小写来比较两个字符串是否一致,有两个方法:一个是把两个字符串都转化为大写或者小写再比较,另外一个是直接使用equalsIgnoreCase方法。ide

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

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

scala> s1.toUpperCase == s2.toUpperCase
res8: Boolean = true

scala> s1.equalsIgnoreCase(s2)
res9: Boolean = true

须要注意的是,使用以上两个方法的时候,"."号左边的字符串不能为空。es5

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

scala> s4.equalsIgnoreCase(s2)
java.lang.NullPointerException
  ... 32 elided

scala> s4.toUpperCase == s2.toUpperCase
java.lang.NullPointerException
  ... 32 elided

Scala中的==定义在AnyRef类中,在Scala API文档中的解释为。x == that:首先判断x是否为空,若是x为空而后判断that是否为空,若是x不为空那么调用x.equals(that)来判断是否相等。scala