简体   繁体   中英

Comparison in Scala

What is the difference between val a=new String("Hello") and val a="Hello"

Example:

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

Similarly:

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

eq compares memory references.

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.

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

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

Example:

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

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

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?

First of all eq (and its opposite ne ) are used for what is called reference equality.

The behavior you observed is the result of what's technically known as string interning and is the inherited behavior from Java. Scala makes use of java.util.String under the hood. You can observe this in the REPL:

scala> val s = "Hello World!"
s: String = Hello World!

scala> s.isInstanceOf[java.lang.String]
res1: Boolean = true

You can see a general explanation of eq, ne, and == here .

To learn about JVM string interning see this Wikipedia article .

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