string - 如何在scala中比较两个字符串?

标签 string scala equality

我想在 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 guidestrings

来自“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)."

关于string - 如何在scala中比较两个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26297473/

相关文章:

string - 如何在知道需要多大之前分配一个字符串

python - 从字符串对象初始化的列表和元组

scala - 相当于Ruby在Scala中的#tap方法

.net 3.5 List<T> 相等和 GetHashCode

json - 比较Scala中的json相等性

arrays - 如何在golang中gzip字符串并返回字节数组

c# - 使用变量赋值与重复方法

scala for 循环很奇怪

scala - 使用流打印列表中的元素

swift - 我如何在 Swift 4 中测试具有关联值的枚举案例的等效性