-
No mutable state at all (
var
variables, mutable lists, etc.) -
To be done...
-
Day 1
-
Day 2
-
Day 3
-
Day 4
-
Day 5
-
Day 6
-
Day 7
-
Day 8
-
Day 9
-
Day 10
I know that lots of stdlib functions (like map
, sumOf
, etc.) use mutable state under the hood.
But that mutable stays in place meaning that I can implement such functions without
any mutability, so I still allowed to use them.
You may ask how one will create loops which obviously use a concept of a mutable variable and are obviously required to solve almost any task?
They will be emulated using tail-recursive functions like this:
fun loop(index: Int) {
println(index)
loop(index = index + 1)
}
This creates infinite loop without any mutability.
- But it will throw stackoverflow exception!!! – One may say
And they will be absolutely correct. It will throw exception unless we add
a special modifier called tailrec
which optimizes tail recursion and
unwraps it back to loops after compilation. So:
tailrec fun loop(index: Int) {
println(index)
loop(index = index + 1)
}
This will not throw any exception and will infinitely print natural numbers.