在 List 的情况下,Scala 的 equals 方法如何工作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11123393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:15:43  来源:igfitidea点击:

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

listscalaequals

提问by John Threepwood

list1 == list2

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

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

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

(我敢肯定,以前有人问过这个问题,但我在 Google & Co 上找不到很好的答案)

回答by Rex Kerr

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.

您可以通过查看 Scaladoc 并找出它的定义位置,然后查看源代码来为任何方法找到这一点。如果您从在线文档开始,只需单击即可完成所有操作:转到该方法,单击左侧的箭头将其打开,您将看到一个覆盖类的列表。转到第一个,并查看源。

Anyway, in this case, GenSeqLike, a supertrait of Listand many other collections, defines equalsas a canEqualcheck followed by sameElements. In turn, sameElementschecks 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 hasNexton each and then comparing the elements with equals.

不管怎样,在这种情况下,GenSeqLike,的supertraitList和许多其他收藏品,定义equalscanEqual检查之后sameElements。依次sameElements检查两个参数是否都是LinearSeqs,如果是,则通过将头和尾一一分开来对每对元素调用 equals。否则,它默认使用迭代器,调用hasNext每个,然后将元素与equals.

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

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