Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Scala's equals method work in the case of a List?

Tags:

list1 == list2 

To do the above check, will Scala iterate through both lists and call equals on each pair of elements ?

(I am sure, this question has been asked before, but I could not find a good answer with Google & Co)

like image 613
John Threepwood Avatar asked Jun 20 '12 15:06

John Threepwood


People also ask

Does equals work for list Java?

Java List equals() Method. The equals() method of List interface compares the specified object with this collection for equality. It returns a Boolean value true if both the lists have same elements and are of the same size.

Why do we use =( equal operator in Scala function?

equals Method: The equals method used to tests value equality. if x equals y is true if both x and y have the same value. They do not need to refer to the identical instance.


1 Answers

You can find this out yourself for any method by looking at the Scaladoc and finding out where it's defined, and then looking at the source. If you start with the online docs, you can do this all just with clicking: go to the method, open it up by clicking on the arrow on the left, and you'll see a list of overriding classes. Go to the first one, and look at the source.

Anyway, in this case, GenSeqLike, a supertrait of List and many other collections, defines equals as a canEqual check followed by sameElements. In turn, sameElements checks whether both arguments are LinearSeqs, and if so, calls equals on each pair of elements by splitting the head and tail apart one by one. Otherwise it defaults to using iterators, calling hasNext on each and then comparing the elements with equals.

So, long story short: yes, it calls equals on each pair of elements (stopping as soon as it finds a mismatch).

like image 149
Rex Kerr Avatar answered Oct 10 '22 15:10

Rex Kerr