如何在scala中比较两个字符串? [英] How to compare two strings in scala?

查看:824
本文介绍了如何在scala中比较两个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想比较Scala中的两个字符串。例如,

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

我的字符串是:

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中,您可以使用 == 平等

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

=方法在AnyRef类中定义。由于这些方法首先检查null值,然后在第一个对象上调用equals方法以查看两个对象是否相等,因此您不必进行特殊的null检查。

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

请参见 Scala入门指南字符串

摘自 Scala编程语言概述
第二版


值之间的相等操作 == 旨在使
相对于类型的表示形式。对于值
类型,它是自然的(数字或布尔值)等式;对于引用
类型, == 被视为等于的别名方法来自
java.lang.Object 。该方法最初定义为引用
相等,,但打算在子类中重写以实现
这些子类的自然平等概念
。例如,值类型的
盒装版本将实现一个equals方法,其中
会比较这些盒装值。 ==始终意味着引用类型上的
引用相等,虽然实现
的效率更高,但它还会引入严重的一致性问题
,因为等值的盒装版本可能不再相等
重复ct = =。在某些情况下,需要引用相等,而不是
用户定义的相等。一个例子是哈希约束,其中效率是
最重要的。对于这些情况,类 AnyRef 定义了一个附加的 eq
方法,该方法不能被覆盖,并实现为引用
相等性(即,其行为像Java中的
== 来引用类型)。

"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)."

这篇关于如何在scala中比较两个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆