在Groovy中缺少生成器/ yield关键字的解决方法 [英] Workaround for lack of generators/yield keyword in Groovy
问题描述
sql.eachRow
,以便在需要Collection或Iterator的DSL上下文中使用它。我试图去的用例是流JSON生成 - 我想要做的是这样的: def generator = {sql.eachRow {yield it}}
jsonBuilder.root {
statusOK
rows generator()
}
$ c $您需要继续支持(或类似)才能使其在一定程度上发挥作用。 Groovy没有延续,JVM也没有延续。通常延续传球风格的作品,但然后eachRow将不得不支持的方法,它当然不会。所以我看到的唯一方法是使用线程或类似的东西的临时解决方案。所以,也许这样的事情会对你有用:
def sync = new java.util.concurrent.SynchronousQueue()
Thread.start {sql.eachRow {sync.put(it)}}
jsonBuilder.root {
statusOK
rows sync.take()
}
我不是说这是一个很好的解决方案,只是一个随机的消费者生产者工作区你的问题。
Wondering if there is a way I can use sql.eachRow
like a generator, to use it in a DSL context where a Collection or Iterator is expected. The use case I'm trying to go for is streaming JSON generation - what I'm trying to do is something like:
def generator = { sql.eachRow { yield it } }
jsonBuilder.root {
status "OK"
rows generator()
}
解决方案 You would need continuation support (or similiar) for this to work to some extend. Groovy does not have continuations, the JVM also not. Normally continuation passing style works, but then the method eachRow would have to support that, which it of course does not. So the only way I see is a makeshift solution using threads or something like that. So maybe something like that would work for you:
def sync = new java.util.concurrent.SynchronousQueue()
Thread.start { sql.eachRow { sync.put(it) } }
jsonBuilder.root {
status "OK"
rows sync.take()
}
I am not stating, that this is a good solution, just a random consumer-producer-work-around for your problem.
这篇关于在Groovy中缺少生成器/ yield关键字的解决方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!