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

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.

主站蜘蛛池模板: 九寨沟县| 资兴市| 丹东市| 苏尼特左旗| 武定县| 潼关县| 勐海县| 余江县| 巴楚县| 雅安市| 东至县| 盱眙县| 宿松县| 航空| 礼泉县| 溆浦县| 林甸县| 白河县| 响水县| 眉山市| 天气| 绥芬河市| 亚东县| 兴安盟| 蒲江县| 九台市| 南雄市| 弥勒县| 镇宁| 加查县| 榆树市| 交城县| 太原市| 枣强县| 都兰县| 台东市| 城固县| 玉林市| 利津县| 建宁县| 乐清市|