Pure functions
- Kotlin course
- Advanced
- Lesson 50/83
- 5 min
Learn pure functions and side effects.
Pure functions
A pure function returns the same output for the same input and has no side effects. It does not mutate global state or perform I/O. It is easy to test and cache.
Example: fun double(n: Int): Int { return n * 2 }. This is pure; for the same n it always returns the same result. In contrast, fun now(): Long { return System.currentTimeMillis() } is impure; each call returns a different value. Purity is essential in functional programming.
Side effects and determinism
A function's side effect is changing external state or performing I/O. Deterministic means the same input always yields the same output. Pure functions satisfy both.
Example: fun square(n: Int): Int { return n * n } is both side-effect free and deterministic. In contrast, fun log(msg: String) { println(msg) } has a side effect (it performs I/O). Side-effect free functions are safe in parallel execution; they need no locks.
Practice Write a pure square function
Define a pure function square(n: Int): Int whose body returns n * n. In main call println(square(5)) and println(square(7)).
Starter code
// square function: returns n * n
// in main print the square of two numbersSample solution
fun square(n: Int): Int {
return n * n
}
fun main() {
println(square(5))
println(square(7))
}Expected output
25 49
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the pure function body
fun double(n: Int): Int {
____
}
fun double(n: Int): Int {
return n * 2
}
Explanation: return n * 2 is pure and deterministic.
2 Which of these is a pure function?
- fun print(s: String) { println(s) }
- fun double(n: Int) = n * 2 Correct answer
- fun time() = System.currentTimeMillis()
- fun read() = readLine()
Explanation: double(n) is side-effect free and deterministic.
3 Match the pure-function parts
| Term | Meaning |
|---|---|
double(n: Int) |
Pure function |
System.currentTimeMillis() |
Side effect |
return n * 2 |
Deterministic body |
println(msg) |
I/O side effect |