How make tail recursion in scala from Future.foreach call back?

845 Views Asked by At

Consider a scala code:

def myRecursiveFunction(id:string):Unit= {
    myAsyncDao.search(id).foreach {response=>
        myRecursiveFunction(response.id)
    }
}
//myAsyncDao.search returns a Future
//response have id field for further computations

If I put @tailrec on top op function, compile complains Recusive call not in tail position.

Can it be optimizated as tail recursion?

1

There are 1 best solutions below

2
On

How about

def myRecursiveFunction(id:string):Future[Unit]= {
    myAsyncDao.search(id) flatMap {response=>
        myRecursiveFunction(response.id)
    }
}

Update:

def search(id: Future[Int]) = Future { 5 }

@tailrec
def myRecursiveFunction(id: Future[Int]):Future[Unit]= {
    val response = search(id)
    myRecursiveFunction(response)    
}