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更能说明上面的结论;

==在AnyRef中是一个函数,其定义如下:

/** 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的结果也不会抛出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字符串做一些函数操作,则会抛出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蓝色显示

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。