Memoization Function In Kotlin

The following solution works for single-argument functions. If you want to created a cached version of the function bar you simply declare it like this:

val cachedBar = makeFunctionCache({ bar(it) })

The implementation stores the cache in a closure so that you don't need to put it in a dedicated class:

fun <X, R> makeFunctionCache(fn: (X) -> R): (X) -> R {
    val cache: MutableMap<X, R> = HashMap()
    return {
        cache.getOrPut(it, { fn(it) })
    }
}

By the nature of the problem, you need a class field to store your cache (the cached value or a caching object or a delegate). So you have to declare a val in the class somewhere, since functions can't do that.

Note that when you declare your buildHiearchy value, you get two things in one: you store a Memoize<..>(..) object in a class field and you get invoke() function (declared somewhere else, but still..). I know of no way you can declare a function and get the field storage with no additional syntax.

The code snippet uses outdated syntax. Fix like this (no parentheses):

val buildHiearchy = Memoize<LocalDate, Node>({date -> buildHierarchy(date)})

Use Map.computeIfAbsent

val map = HashMap<LocalDate, Node>()
val key = LocalDate("Jun 14, 2022")

val value = map.computeIfAbsent(key) { 
    Node("My fancy node") 
}

The calculation will be executed only once and stored in the map