Groovy运营商如何运作? [英] How does the Groovy in operator work?
问题描述
x in y
意味着 y.contains(x)
,有时它似乎调用 y .isCase(x)
。 Groovy如何知道要调用哪一个? Groovy知道哪些使用.contains方法的特定类或一组类?还是由一个对象上的方法的存在引发的行为?是否有任何情况下,in运算符完全变成了其他东西?
我做了一些实验,看起来像
运算符仅基于 isCase
方法,如以下代码所示:
class MyList extends ArrayList {
boolean isCase(Object val){
return val == 66
}
}
def myList = new MyList()
myList<< 55
55 in myList //返回false,但myList.contains(55)在myList中返回true
66 //返回true,但myList.contains(66)返回false
对于JDK集合类,我想这看起来像运算符中的是基于
contains()
因为 isCase()
调用 contains()
对于这些类。
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?
I did some experimentation and it looks like the in
operator is based on the isCase
method only as demonstrated by the following code
class MyList extends ArrayList {
boolean isCase(Object val) {
return val == 66
}
}
def myList = new MyList()
myList << 55
55 in myList // Returns false but myList.contains(55) returns true
66 in myList // Returns true but myList.contains(66) returns false
For the JDK collection classes I guess it just seems like the in
operator is based on contains()
because isCase()
calls contains()
for those classes.
这篇关于Groovy运营商如何运作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!