对于列表,Scala的equals方法如何工作? [英] How does Scala's equals method work in the case of a List?

查看:70
本文介绍了对于列表,Scala的equals方法如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

list1 == list2

要做上述检查,Scala会遍历两个列表并在每对元素上调用equals吗?

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

(我敢肯定,这个问题已经被问过了,但是我在Google& Co找不到很好的答案)

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

推荐答案

您可以通过查看Scaladoc并找出其定义位置,然后查看源代码来自己找到适用于任何方法的方法.如果您从在线文档开始,则只需使用单击:转到方法,通过单击左侧的箭头将其打开,您将看到一个覆盖类的列表.转到第一个,然后查看源.

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.

无论如何,在这种情况下,GenSeqLikeList和许多其他集合的超例,将equals定义为canEqual支票,后跟sameElements.反过来,sameElements检查两个参数是否都是LinearSeq,如果是,则通过将头和尾一一分开,在每对元素上调用equals.否则,默认情况下将使用迭代器,在每个迭代器上调用hasNext,然后将元素与equals进行比较.

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.

因此,长话短说:是的,它在每对元素上调用equals(一旦发现不匹配就停止).

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

这篇关于对于列表,Scala的equals方法如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆