val s2 = "Hello"s2: String = Helloscala> val s3 = "H" + "ello"s3: String = Helloscala> val s4 = Array("H", "e", "l", "l", "o")。Scala判断字符串是否相等。" />

Scala判断字符串是否相等

在Scala中可以通过==判断字符串实例是否相等,eg.

scala> val s1 = "Hello" s1: String = Helloscala> val s2 = "Hello" s2: String = Helloscala> val s3 = "H" + "ello" s3: String = Helloscala> val s4 = Array("H", "e", "l", "l", "o").mkString("") s4: String = Helloscala> s1 == s2 res0: Boolean = truescala> s1 == s3 res1: Boolean = truescala> s1 == s4 res2: Boolean = truescala> s2 == s3 res3: Boolean = truescala> s1.eq eqequalsequalsIgnoreCasescala> s1.equals(s2) res4: Boolean = truescala> s1.equals(s3) res5: Boolean = truescala> s1.equals(s4) res6: Boolean = truescala> s1.eq(s2) res7: Boolean = truescala> s1.eq(s3) res8: Boolean = truescala> 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)`. * *@paramarg0the 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 :11: error: not found: value s4 s4 = null ^ :12: error: not found: value s4 val $ires0 = s4 ^scala> val s4:String = null s4: String = nullscala> val s5:String = null s5: String = nullscala> 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 = Amgenscala> val s7 = "amgen" s7: String = amgenscala> s6 == s7 res4: Boolean = falsescala> s6.equalsIgnoreCase(s7) res5: Boolean = true

\033[1q Scala不推荐使用null,可以使用Option代替
【Scala判断字符串是否相等】Markdwon测试
"\033[34mdanran\033[0m" danran蓝色显示

    推荐阅读