class Fetcher() {
type MyData = Int
private var called = 0
def isSeenAllData = called > 5
def fetch: Either[Exception, Seq[MyData]] =
if (isSeenAllData) Left(new Exception("too many calls!"))
else {
called += 1
Right(Seq(1 to called: _*))
}
}
>> defined class Fetcher
val lazyList = LazyList.unfold(new Fetcher()) { f => if (f.isSeenAllData) None else Some((f.fetch, f)) }
>> lazyList: LazyList[Either[Exception, Seq[Int]]] = LazyList(Right(List(1)), Right(List(1, 2)), Right(List(1, 2, 3)), Right(List(1, 2, 3, 4)), Right(List(1, 2, 3, 4, 5)), Right(List(1, 2, 3, 4, 5, 6)))
To make sure the list is actually lazy
class LazyCheck(fetcher: Fetcher) {
val lazyList = LazyList.unfold(fetcher) { f => if (f.isSeenAllData) None else Some((f.fetch, f)) }
}
defined class LazyCheck
@ val f = new Fetcher
f: Fetcher = ammonite.$sess.cmd5$Fetcher@4b9b5da5
@ f.isSeenAllData
res9: Boolean = false
@ val check = new LazyCheck(f)
check: LazyCheck = ammonite.$sess.cmd7$LazyCheck@c19bb2a
@ f.isSeenAllData
res11: Boolean = false
@ check.lazyList.headOption
res12: Option[Either[Exception, Seq[Int]]] = Some(Right(List(1)))
@ f.isSeenAllData
res13: Boolean = false
@ check.lazyList
res14: LazyList[Either[Exception, Seq[Int]]] = LazyList(Right(List(1)), Right(List(1, 2)), Right(List(1, 2, 3)), Right(List(1, 2, 3, 4)), Right(List(1, 2, 3, 4, 5)), Right(List(1, 2, 3, 4, 5, 6)))
@ f.isSeenAllData
res15: Boolean = true