How does Scala's equals method work in the cas

2019-06-14 23:19发布

问题:

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)

回答1:

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).