问题描述
我正在编写一个 Scala 库,以便更轻松地查询分页的 JSON API.每个 API 调用都会返回一个如下所示的对象:
I'm writing a Scala library to make querying an paginated JSON API easier. Each API call returns an object that looks something like this:
{
"count": 100,
"current_page": 1,
"total_pages": 2,
"records": [
...
]
}
我想要一个返回某种迭代器的函数,比如 MyIterator[Record].在 Scala 世界中是否有任何标准方法可以做到这一点,甚至标准库中的构造可以帮助我?
I'd like to have a function that returned some sort of iterator like MyIterator[Record]. Are there any standard ways to do this in the Scala world, perhaps even constructs in the standard library that could help me?
如果有帮助的话,我通常使用 lift-json 来解析 JSON.
I'm using lift-json generally for my JSON parsing, if that's helpful.
谢谢.
推荐答案
如果你有一个 Iterator[Iterator[A]]
你可以使用 flatten
来产生一个 Iterator[Iterator[A]]
code>Iterator[A] 将所有嵌套的迭代器链接在一起:
If you have an Iterator[Iterator[A]]
you can use flatten
to produce an Iterator[A]
which chains all the nested Iterators together:
scala> Iterator(Iterator(1, 2), Iterator(3, 4)).flatten.toList
res0: List[Int] = List(1, 2, 3, 4)
结合 Iterator 上的一种工厂方法 companion对象,你可以把它变成一个单行:
Combined with one of the factory methods on the Iterator companion object, you could probably turn this into a one-liner:
Iterator.range(1, pageCount).map(i: Int => fetchPage(i)).flatten
如果您只能通过检索页面来获取页面计数,则可能需要更复杂一些……例如:
It might need to be a bit more complex if you can only get the page count by retrieving a page... something like:
val (firstPage, pageCount) = getFirstPageWithCount()
firstPage ++ (Iterator.range(2, pageCount).map(fetchPage).flatten)
这篇关于为分页 API 制作 Scala 迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!