Skip to content

Instantly share code, notes, and snippets.

@markandrus
Last active August 29, 2015 14:13
Show Gist options
  • Save markandrus/ed1df0e1fa810632c9bc to your computer and use it in GitHub Desktop.
Save markandrus/ed1df0e1fa810632c9bc to your computer and use it in GitHub Desktop.
chunked.scala
object Chunked {
def getItems(start: Int, count: Int): List[Int] = {
// Simulate doing I/O to get the items.
val items = List.range(start*count, (start*count)+count)
println(s"> Database returned: ${items}")
items
}
def chunked(count: Int): Stream[Int] = {
def loop(start: Int): Stream[Int] =
getItems(start, count).toStream #::: loop(start+1)
loop(0)
}
lazy val items = chunked(10).toIterator
}
// $ scala -i chunked.scala
// Loading chunked.scala...
// defined object Chunked
//
// Welcome to Scala version 2.11.4 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_65).
// Type in expressions to have them evaluated.
// Type :help for more information.
//
// scala> Chunked.items.next()
// > Database returned: List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
// res0: Int = 0
//
// scala> Chunked.items.next()
// res1: Int = 1
//
// scala> Chunked.items.next()
// res2: Int = 2
//
// scala> Chunked.items.next()
// res3: Int = 3
//
// scala> Chunked.items.next()
// res4: Int = 4
//
// scala> Chunked.items.next()
// res5: Int = 5
//
// scala> Chunked.items.next()
// res6: Int = 6
//
// scala> Chunked.items.next()
// res7: Int = 7
//
// scala> Chunked.items.next()
// res8: Int = 8
//
// scala> Chunked.items.next()
// res9: Int = 9
//
// scala> Chunked.items.next()
// > Database returned: List(10, 11, 12, 13, 14, 15, 16, 17, 18, 19)
// res10: Int = 10
//
// scala>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment