在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> s1 == s2
res0: Boolean = true
scala> s1 == s3
res1: Boolean = true
==
在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
网友评论