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.bazbo.222
08/27/2025, 7:38 AMgetOrPut
way of doing things. It's fun :))bazbo.222
08/27/2025, 7:49 AMfoo(bar, baz, qux)
of three (or more) parameters. What's the most idiomatic way of doing it? I've perused [this StackOverflow answer](https://stackoverflow.com/questions/822322/how-to-implement-a-map-with-multiple-keys), and the idea of a MultiKeyMap seems enticing. I've tried just using a plain MutableMap<Pair<K1, K2>,V>
, but maybe due to how pairs are hashed under the hood or something, it didn't have the expected / desired behaviour for my use case.
So, would you implement n
maps for a function that takes n
arguments? Or is there a smarter approach to the underlying data structure here?Joffrey
08/27/2025, 8:13 AMbazbo.222
08/27/2025, 11:37 AM