Writing the function body

In functional programming, we avoid mutating variables. In an imperative language, you would typically implement nbOfMonthsSaving by using a while loop. It is also possible to do so in Scala, but it is a better practice to only use immutable variables. One way of solving this problem is to use recursion:

def nbOfMonthsSaving(interestRate: Double, nbOfMonthsInRetirement: Int,
netIncome: Int, currentExpenses: Int, initialCapital: Double): Int = {
def loop(months: Int): Int = {
val (capitalAtRetirement, capitalAfterDeath) = simulatePlan(
interestRate = interestRate,
nbOfMonthsSaving = months, nbOfMonthsInRetirement =
nbOfMonthsInRetirement,
netIncome = netIncome, currentExpenses = currentExpenses,
initialCapital = initialCapital)

val returnValue =
if (capitalAfterDeath > 0.0)
months
else
loop(months + 1)
returnValue
}
loop(0)
}

We declare the recursive function inside the body of the function, as it is not meant to be used anywhere else. The loop function increments months by 1 until the calculated capitalAfterDeath is positive. The loop function is initiated in the body of nbMonthsSaving with months = 0. Note that IntelliJ highlights the fact that the loop function is recursive with a kind of @ sign.

Now, we can run our unit test again, and it should pass. However, we are not quite done yet. What happens if you can never reach a month that would satisfy the condition capitalAfterDeath > 0.0? Let's find out by writing another test.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset