bazbo.222
08/25/2025, 4:24 PMfoo(arg)
, foo(arg)
gets calculated, but the second, third etc. times that I call foo
after that, foo(arg)
just returns the already computed, stored value.
E.g. in Python, this exists in the form of the @Memoize
operator, if anyone is familiar with that.
Is there any way to achieve this in Kotlin or should I just implement the memoization mechanism myself.Joffrey
08/25/2025, 4:26 PMcached(key, args) { ... }
Joffrey
08/25/2025, 4:27 PMJoffrey
08/25/2025, 4:28 PMYoussef Shoaib [MOD]
08/25/2025, 4:35 PMMemoizedDeepRecursiveFunction
I believe, but yes you can just as well do your own higher-order functionbazbo.222
08/25/2025, 4:59 PMEither<U,V>
behaves a lot like Rust's Result<T,E>
enum or like TypeScript's union types; so Youssef, you've made me all the more curious about checking it out. Thanks, guys!Joffrey
08/25/2025, 5:05 PMYoussef Shoaib [MOD]
08/25/2025, 5:07 PMjoseph_ivie
08/25/2025, 8:15 PMprivate val results = HashMap<Int, Int>()
fun memoizedFib(number: Int): Int = if(number <= 1) number else results.getOrPut(number) {
memoizedFib(number - 1) + memoizedFib(number - 2)
}
memoizedFib(11)
Note this will have concurrency issues unless you use ConcurrentHashMap
instead.