Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala class and case class == comparison

Tags:

equality

scala

I don't quite understand why when we compare two instance with the same properties of a class without overriding the equals method that it will give a false. But it will give a true when we compare two instances of a case class. For example

 class A(val name: String, val id: Int)  case class B(name: String, id: Int)   object Test {     val a1 = new A('a',1)     val a2 = new A('a',1)     println(a1 == a2)   //this returns false      var b1 = B('b',1)     var b2 = B('b',1)     println(b1 == b2)   //this returns true   } 

Could someone explain why, please?

like image 493
peter Avatar asked Feb 28 '14 18:02

peter


People also ask

What is the difference between Case class and class in Scala?

A class can extend another class, whereas a case class can not extend another case class (because it would not be possible to correctly implement their equality).

What is the case class in Scala?

What is Scala Case Class? A Scala Case Class is like a regular class, except it is good for modeling immutable data. It also serves useful in pattern matching, such a class has a default apply() method which handles object construction. A scala case class also has all vals, which means they are immutable.

What is difference between Case class and case object in Scala?

A case class can take arguments, so each instance of that case class can be different based on the values of it's arguments. A case object on the other hand does not take args in the constructor, so there can only be one instance of it (a singleton, like a regular scala object is).

What is the benefit of case class in Scala?

While all of these features are great benefits to functional programming, as they write in the book, Programming in Scala (Odersky, Spoon, and Venners), “the biggest advantage of case classes is that they support pattern matching.” Pattern matching is a major feature of FP languages, and Scala's case classes provide a ...


1 Answers

A case class implements the equals method for you while a class does not. Hence, when you compare two objects implemented as a class, instead of case class, what you're comparing is the memory address of the objects.

It's really the same issues as when you have to deal with equality in Java. See this Artima blog post about writing equals in Java (and Scala) written by Bill Venners, Martin Odersky, and Lex Spoon.

like image 92
wheaties Avatar answered Oct 15 '22 01:10

wheaties