1

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?

Cherry
  • 31,309
  • 66
  • 224
  • 364
  • 2
    As you can read [in this answer](http://stackoverflow.com/a/16986416/2522681) your solution does not require tail recursion because the stack does not grow anyway. – Michael Lang Jun 24 '15 at 07:02

1 Answers1

0

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)    
}
digit plumber
  • 1,140
  • 2
  • 14
  • 27
  • Did you even try it before posting ? It does not work still the same error. – curious Jun 24 '15 at 07:06
  • With the exception that the OP's `search` function does not take a `Future[Int]` but instead a `String` which makes the situation more complex, unfortunately. – Michael Lang Jun 24 '15 at 08:11