Comparison in Scala

后端 未结 2 352
暗喜
暗喜 2020-12-17 00:49

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

Example:

val a=\"Hello\"
val b=\"Hello\"
a e         


        
2条回答
  •  执念已碎
    2020-12-17 01:00

    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?

提交回复
热议问题