I will give a simplified code to explain my question easily:
val balance = 10
for(elem <- dataList) yield (interest(elem, balance))
.
How can I use this newly returned value for the next element in my data list in yield so I could keep up-to-date my balance for the next elements in the list?
i.e. for(elem <- dataList) yield (interest(elem, newBalanceFromPreviousYield))
I think, there is no easy way to use it just with yield
. Your use-case reminds fold pattern, so, let's use it. We accumulate balance and use it in interest()
invocation:
dataList.foldLeft(List.empty[Int]) { (acc, elem) =>
acc match {
case Nil =>
// if no balances accumulated yet, use default balance = 10
List(interest(elem, balance))
case all@newBalance :: _ =>
// else use accumulated balance
interest(elem, newBalance) :: all
}
}.reverse // we need to reverse result list due to :: usage