Hello, I've a question about maps and potentially ...
# announcements
r
Hello, I've a question about maps and potentially lambdas, I've a map mapping int to objects creation, something like this: val menuIdToItems: Map<Int, MyObject> by lazy { mapOf( menu1 to Item1.newInstance(), menu2 to Item2.newInstance(), menu3 to item3.newInstance(), ) It's working fine, BUT I just realised that when I evaluate menuIdToItems[menu1], I actually need a NEW INSTANCE every time I evaluate menuIdToItems[menu1]. Right now, If I evaluate menuIdToItems[menu1] two times, second time will return the same instance that I got the first time. Is there a way to do this using a map?
g
wrap
Item1.newInstance()
to lambda and then:
menuIdToItems[menu1]()
or
menuIdToItems[menu1].invoke()
And change map type to something like
Map<Int, () -> MyObject>
r
Note that I still want to keep returning the same instance for the case item2 and item3, If I do that, wouldn't have a type mismatch for other cases or I'll have to return new instance for all of them?
g
you need some abstraction with memoization
it means that create lambda with static value
not sure what is correct term for that, memoization or Identitiy (like in FP)
Copy code
fun <T> memoized(instance: T): () -> T = { instance }

val menuIdToItems: Map<Int, () -> MyObject> by lazy {
        mapOf(
                menu1 to { Item1.newInstance() },
                menu2 to memoized(Item2.newInstance()),
                menu3 to memoized(item3.newInstance()),
        )
}
r
Awesome, I'm just trying what you suggest.
g
yeah, probably bad naming, also instance creation will not be lazy, probably better to use something like:
Copy code
class Cached<T>(builder: () -> T) : () -> T {
    private val instance by lazy { builder() }
    override fun invoke(): T = instance
}

val menuIdToItems: Map<Int, () -> MyObject> by lazy {
        mapOf(
                menu1 to { Item1.newInstance() },
                menu2 to Cached { Item2.newInstance() },
                menu3 to Cached { item3.newInstance() },
        )
}
In this case instance of each item will be created only on first access and cached