Comparison in Scala

What is the difference between val a=new String("Hello")andval 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
+4
source share
2 answers

eq compares memory references.

String literals are placed in a string constant pool, so in the first example they use the same memory reference. This is a behavior that comes from Java ( scala.Stringbuilt on top java.lang.String).

In the second example, you allocate two instances at runtime, so when you compare them, they are in different places in memory.

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

, ( ), == ( equals) Scala.

:

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

Java, == - , eq Scala.

, == equals null (==). : == .equals Scala?

+12

eq ( ne) .

, , , Java. Scala java.util.String . REPL:

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

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

eq, ne == .

JNM string interning, . .

0

Source: https://habr.com/ru/post/1651392/


All Articles