== for case class and non-case class in Scala

I study Scala and came across the following riddle.

I can define the following case classes:

abstract class Expr
case class Number(n: Int) extends Expr

When I create two instances from a class Numberand compare them

val x1 = Number(1)
val x2 = Number(1)
x1 == x2

I have the following result:

x1: Number = Number (1)

x2: Number = Number (1)

res0: Boolean = true

So, x1they x2coincide.

However, if I omit the modifier casein the class definition Number, i.e.

abstract class Expr
class Number(n: Int) extends Expr

and then compare two instances from the class Numberin the same way

val x1 = new Number(1)
val x2 = new Number(1)
x1 == x2

I have the following output:

x1: Number = Number @ 1175e2db

x2: Number = Number @ 61064425

res0: Boolean = false

It says that at this time x1, and x2different.

, ? case ?

, Pan

+4
1

case Scala, equals, (.. ).

: http://www.scala-lang.org/old/node/107

case Scala equals, toString.

case, , == () . , , .

: ? ?

+9

All Articles