加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何比较scala中的两个字符串?

发布时间:2020-12-16 09:28:16 所属栏目:安全 来源:网络整理
导读:我想比较scala中的两个字符串.例如, 我的字符串是: scala javascala java c++scala c++ 我想比较字符串 每个字符串都有“scala c” 结果应该是, scala c++ = scala java // falsescala c++ = scala java c++ // falsescala c++ = scala c++ // true 解决方
我想比较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).”

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读