Scala 中的比较 [英] Comparison in Scala

查看:49
本文介绍了Scala 中的比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

val a=new String("Hello")val a="Hello"

示例:

val a="Hello"
val b="Hello"
a eq b
res:Boolean=True

同样:

val a=new String("Hello")
val b=new string("Hello")
a eq b
res:Bolean=False

推荐答案

eq 比较内存引用.

字符串字面量放在字符串常量池中,因此在第一个示例中它们共享相同的内存引用.这是来自Java(scala.String 建立在 java.lang.String 之上).

String literals are put in a string constants pool, so in the first example they share the same memory reference. This is a behavior that comes from Java (scala.String is built on top of java.lang.String).

在第二个示例中,您在运行时分配两个实例,因此当您比较它们时,它们位于不同的内存位置.

In the second example you're allocating two instances at runtime so when you compare them they're are at different memory locations.

这和Java完全一样,所以你可以参考这个答案了解更多信息:"text" 和有什么区别?和新的字符串(文本")?

This is exactly the same as Java, so you can refer to this answer for more information: What is the difference between "text" and new String("text")?

现在,如果您想比较它们的值(而不是它们的内存引用),您可以在 Scala 中使用 ==(或 equals).

Now, if you want to compare their values (as opposed to their memory references), you can use == (or equals) in Scala.

示例:

val a = new String("Hello")
val b = new String("Hello")
a eq b // false
a == b // true
a equals b // true

这与 Java 不同,其中 == 是一个操作符,其行为类似于 Scala 中的 eq.

This is different than Java, where == is an operator that behaves like eq in Scala.

还要注意 ==equals 在处理 null 值(==代码> 一般建议).有关该主题的更多信息:Scala 中 == 和 .equals 之间的区别是什么?

Also note that == and equals are slightly different in the way the deal with null values (== is generally advised). More on the subject: Whats the difference between == and .equals in Scala?

这篇关于Scala 中的比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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