简体   繁体   中英

How to compare two strings in scala?

I want to compare two strings in scala. for example,

My Strings are:

scala java
scala java c++
scala c++

I want to compare the string

" scala c++ " with each strings

Results should be,

scala c++ = scala java   // false
scala c++ = scala java c++  // false
scala c++ = scala c++   // true

In Scala you can use == for equality

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

The == method is defined in the AnyRef class. Since the methods first checks for null values, and then calls the equals method on the first object to see if the two objects are equals you dont have to do a special null check;

"test" == null
res0: Boolean = false

See the Scala getting started guide and strings

From " 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 me thod, which cannot be overridden, and is implemented as reference equality (ie, it behaves like == in Java for reference types)."

要添加等式比较,您可以使用!=表示不等式。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM