Groovy in 运算符如何工作?
Groovy“in”运算符在不同情况下似乎意味着不同的东西。有时x in y
表示y.contains(x)
,有时它似乎调用y.isCase(x)
。
Groovy 如何知道要调用哪一个? Groovy 是否知道使用 .contains 方法的特定类或类集?或者该行为是由其中一个对象上的方法的存在触发的?是否存在 in 运算符完全更改为其他内容的情况?
The Groovy "in" operator seems to mean different things in different cases. Sometimes x in y
means y.contains(x)
and sometimes it seems to call y.isCase(x)
.
How does Groovy know which one to call? Is there a particular class or set of classes that Groovy knows about which use the .contains method? Or is the behavior triggered by the existence of a method on one of the objects? Are there any cases where the in operator gets changed into something else entirely?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我做了一些实验,看起来
in
运算符仅基于isCase
方法,如以下代码所示对于 JDK 集合类,我想它看起来就像
in
运算符基于contains()
,因为isCase()
为这些类调用contains()
。I did some experimentation and it looks like the
in
operator is based on theisCase
method only as demonstrated by the following codeFor the JDK collection classes I guess it just seems like the
in
operator is based oncontains()
becauseisCase()
callscontains()
for those classes.in
是“成员资格运算符”。来自 Groovy 3 的文档< /a> (强调我的):
因此,Groovy 总是调用
isCase
,在List
的情况下映射到contains
。in
is the "Membership operator".From the documentation for Groovy 3 (emphasis mine):
So, Groovy always calls
isCase
, which in case of aList
maps tocontains
.其实都是基于isCase的。 Groovy 添加了 基于 contains 方法的 Collections 的 isCase 方法。任何具有 isCase 的类都可以与 in 一起使用。
It's actually all based on isCase. Groovy adds an isCase method to Collections that is based on the contains method. Any class with isCase can be used with in.