官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 盐源县| 儋州市| 布尔津县| 蓬莱市| 牙克石市| 酒泉市| 泰安市| 盘山县| 弥勒县| 大洼县| 东阿县| 疏勒县| 大庆市| 苍溪县| 吉木乃县| 叶城县| 西吉县| 昌乐县| 吉林市| 南召县| 荥阳市| 界首市| 新密市| 万荣县| 保德县| 弥勒县| 寻乌县| 湖口县| 文水县| 杂多县| 甘肃省| 石棉县| 出国| 于田县| 北流市| 安庆市| 宁晋县| 五华县| 普陀区| 绵阳市| 青田县|