June 2018
Intermediate to advanced
310 pages
6h 32m
English
If our function always returns the same output for the same input, we could easily map between previous input and output, and use it as a cache. That technique is called memoization:
class Summarizer { private val resultsCache = mutableMapOf<List<Int>, Double>() fun summarize(numbers: List<Int>): Double { return resultsCache.computeIfAbsent(numbers, ::sum) } private fun sum(numbers: List<Int>): Double { return numbers.sumByDouble { it.toDouble() } }}
We use a method reference operator, ::, to tell computeIfAbsent to use the sum() method in the event that input wasn't cached yet.
Note that sum() is a pure function, while summarize() is not. The latter will behave differently for the same input. But that's exactly what we want ...
Read now
Unlock full access