def array = [1,2,3,4,5]
println 3 in array
打印true
。对于任何对象,我需要重载以支持in
?
示例:
class Whatever {
def addItem(item) {
// add the item
}
}
def w = new Whatever()
w.addItem("one")
w.addItem("two")
println "two" in w
我知道我可以使这个课程使用公开的集合,但我想改用in
。
答案 0 :(得分:8)
我在Groovy邮件列表上询问过。 Here's线程。答案是isCase
class A
{
def isCase(o) {
return false;
}
}
a = new A()
println 6 in a // returns false
答案 1 :(得分:2)
您可以Whatever
实现Collection或Collection子接口。 Groovy对iterator()
有一个Object
implementation,对于处理聚合对象的运算符来说,Groovy会尝试将Object转换为Collection,然后执行聚合函数。< / p>
或者,您可能能够Whatever
实施Iterable。我仍然试图为此找到一个参考,并编写一个概念验证来验证它。
答案 2 :(得分:1)
我想知道这是否可行,会员运营商(in)未列在Operator Overloading页面上。