在Groovy类中,我希望通过getter和setter将内部DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10)) {
self.toggleLikeSubject.onNext()
}
属性公开为String
。我希望该属性的行为就像我可以使用List
添加元素的常规列表属性。但它不起作用,我必须使用解决方法obj.list << newElement
。
还有其他方法可以在Groovy中完成这个技巧吗?在类中实现的任何方法,将在使用obj.list = obj.list << newElement
运算符时调用?
代码示例:
<<
答案 0 :(得分:1)
Consider the following:
class Test {
String internal = 'a,b,c'
List getList() {
def list = internal.split(',') as List
// this will override so:
// << 'd' becomes appendToList(['d'])
// << ['e','f'] becomes appendToList(['e','f'])
list.metaClass.leftShift = { def x ->
this.appendToList([x].flatten())
}
return list
}
void appendToList(List list) {
internal = internal + "," + list.join(',')
}
void setList(List list) {
internal = list.join(',')
}
}
Note it handles both cases of (a) one item (b) a list of items
def t = new Test()
t.list << 'd'
assert ['a','b','c','d'] == t.list
t.list << ['e','f']
assert ['a','b','c','d','e','f'] == t.list
t.list = ['x','y']
assert ['x', 'y'] == t.list
答案 1 :(得分:0)
尝试使用以下代码
Test t = new Test()
List list = t.getList()
list << 'd'
println list.dump()