我想在 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)."
关于string - 如何在scala中比较两个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26297473/