Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are Buffer and List objects equal (even they are from different classes)?

scala> import scala.collection.mutable.Buffer
import scala.collection.mutable.Buffer

scala> val b = Buffer(1, 2, 3)
b: scala.collection.mutable.Buffer[Int] = ArrayBuffer(1, 2, 3)

scala> val l = List(1, 2, 3)
l: List[Int] = List(1, 2, 3)

scala> b == l
res1: Boolean = true

I was wondering, why the Buffer and List object can be compared with a result of true ?

I always thought, that because they are from different classes, they have to be false when compared. Can someone explain me, why it is implemented this way ?

like image 209
John Threepwood Avatar asked Jun 20 '12 19:06

John Threepwood


2 Answers

From http://www.scala-lang.org/docu/files/collections-api/collections_41.html

The collection libraries have a uniform approach to equality and hashing. The idea is, first, to divide collections into sets, maps, and sequences. Collections in different categories are always unequal. For instance, Set(1, 2, 3) is unequal to List(1, 2, 3) even though they contain the same elements. On the other hand, within the same category, collections are equal if and only if they have the same elements (for sequences: the same elements in the same oder). For example, List(1, 2, 3) == Vector(1, 2, 3), and HashSet(1, 2) == Treeset(2, 1).

It does not matter for the equality check whether a collection is mutable or immutable. (...)

So it's because scala.collection.mutable.Buffer and List belong to the same category (sequence) and equality is then defined as having equal elements.

like image 110
User Avatar answered Oct 20 '22 21:10

User


List and Buffer are both scala.collection.Seq. They have elements, possibly duplicated, that can be enumerated (ie, first element, second element, etc).

The fact that one is a List and the other a Buffer is just an implementation detail.

A better question would be why an scala.collection.immutable.Seq and a scala.collection.mutable.Seq can be equal, and the answer is that the mutability is irrelevant with respect to how they are compared.

like image 21
Daniel C. Sobral Avatar answered Oct 20 '22 19:10

Daniel C. Sobral