Dean Hiller
Dean Hiller

Reputation: 20204

call function until it returns None in scala

is there a scala way to call this function until it returns None (other than the default java way of looping and checking)

def process(
  writer: Option[FileWriter],
  request: SomeRequest
)(nextId: Option[String], pageNumber: Int): Option[String] = {

this function is called in a foldLeft already in another case that I would prefer not to touch. Also, as it is called over and over, I need to pass the return value to the nextId parameter if is Some(nextId) and not a None.

otherwise, I guess I can do a var nextId = retValue but I hate using vars in scala. it feels like I couldn't get it right.

thanks, Dean

Upvotes: 0

Views: 248

Answers (1)

Eduardo
Eduardo

Reputation: 8402

Couldn't you define another function that calls your function, like this:

   import scala.annotation.tailrec

   @tailrec
   def loop(wrt:Option[FileWriter], req:SomeRequest)(nxt:Option[String], pg:Int) = {
     process(wrt, req)(nxt, pg) match {
       case res:Some[String] =>
         loop(wrt, req)(res, pg + 1)
       case None =>
         // whatever you need to do when you are done
     }
   }

EDIT: added explicit @tailrec annotation

Upvotes: 2

Related Questions