在Groovy中缺少生成器/ yield关键字的解决方法 [英] Workaround for lack of generators/yield keyword in Groovy

查看:90
本文介绍了在Groovy中缺少生成器/ yield关键字的解决方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想知道是否有一种方法可以像生成器一样使用 sql.eachRow ,以便在需要Collection或Iterator的DSL上下文中使用它。我试图去的用例是流JSON生成 - 我想要做的是这样的:

  def generator = {sql.eachRow {yield it}} 
jsonBuilder.root {
statusOK
rows generator()
}


  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆