我想比较scala中的两个字符串.例如,
我的字符串是:
scala java
scala java c++
scala c++
我想比较字符串
每个字符串都有“scala c”
结果应该是,
scala c++ = scala java // false
scala c++ = scala java c++ // false
scala c++ = scala c++ // true
在Scala中,您可以使用==进行相等
scala> "scala c++" == "scala java"
res0: Boolean = false
scala> "scala c++" == "scala java c++"
res1: Boolean = false
scala> "scala c++" == "scala c++"
res2: Boolean = true
==方法在AnyRef类中定义.由于方法首先检查空值,然后在第一个对象上调用equals方法以查看两个对象是否相等,您不必进行特殊的空值检查;
"test" == null
res0: Boolean = false
见Scala getting started guide和strings
从“An Overview of the Scala Programming Language
Second Edition”;
“The equality operation == between values is designed to be
transparent with respect to the type’s representation. For value
types,it is the natural (numeric or boolean) equality. For reference
types,== is treated as an alias of the equals method from
java.lang.Object. That method is originally defined as reference
equality,but is meant to be overridden in subclasses to implement the
natural notion of equality for these subclasses. For instance,the
boxed versions of value types would implement an equals method which
compares the boxed values. By contrast,in Java,== always means
reference equality on reference types. While this is a bit more
efficient to implement,it also introduces a serious coherence problem
because boxed versions of equal values might no longer be equal with
respect to ==. Some situations require reference equality instead of
user-dened equality. An example is hash-consing,where eciency is
paramount. For these cases,class AnyRef defines an additional eq
method,which cannot be overridden,and is implemented as reference
equality (i.e.,it behaves like
== in Java for reference types).”