I'm trying to understand how does the LazyList.fill actually works. I implemented a retry logic using LazyList.fill(n). But seems like it is not working as expected.
def retry[T](n: Int)(block: => T): Try[T] = {
val lazyList = LazyList.fill(n)(Try(block))
lazyList find (_.isSuccess) getOrElse lazyList.head
}
Considering the above piece of code, I am trying to execute block with a retry logic. If the execution succeeds, return the result from block else retry until it succeeds for a maximum of n attempts.
Is it like LazyList will evaluate the first element and if it finds true, it skips the evaluation for the remaining elements in the list?
As I already mentiond in the comment, this is exactly what a
LazyListis supposed to do.The elements in a
LazyListare also materialized/computed only when there is demand from an actual consumer.And
findmethod ofLazyListrespect this lazyness. You can find it cleary written in documentation as well - https://www.scala-lang.org/api/2.13.x/scala/collection/immutable/LazyList.html#find(p:A=%3EBoolean):Option[A]So, If the first element succeeds, it will stop at the first element itself.
Also, if you are writing a
retrymethod then you probably also want to stop at first success. Why would you want to continue evaluating theblockeven after the suceess.You might want to better clarify your exact requirements to get a more helpful answer.