🔴 Scala Beginner

What is the difference between == and eq in Scala?

Answer

In Scala, == calls the equals method, providing structural/value equality. For case classes and most standard types, it compares content: List(1,2) == List(1,2) // true, case class P(n: Int); P(1) == P(1) // true. It is null-safe: null == "hello" // false (no NullPointerException). eq checks reference equality — whether two references point to the exact same JVM object: val a = new StringBuilder; val b = a; a eq b // true. This is equivalent to Java's == for objects. ne is the negation of eq. Most Scala code uses == exclusively. Use eq only when you specifically need reference identity — for example, when interoperating with Java code or dealing with object internment.