- Scala Programming Projects
- Mikael Valot Nicolas Jorand
- 224字
- 2021-07-23 16:25:20
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.
- 黑客攻防實戰技術完全手冊:掃描、嗅探、入侵與防御
- Building E-commerce Sites with VirtueMart Cookbook
- 物聯網智慧安監技術
- Hands-On Chatbot Development with Alexa Skills and Amazon Lex
- 物聯網概論(第2版)
- 局域網組建、管理與維護項目教程(Windows Server 2003)
- Spring Cloud微服務架構進階
- WordPress 5 Complete
- 射頻通信系統
- 城市治理一網統管
- 網絡環境中基于用戶視角的信息質量評價研究
- 工業互聯網創新實踐
- AIoT應用開發與實踐
- 沖擊:5G如何改變世界
- Dart Cookbook