Elegant way to defer value calculation of a Map?

I have the situation, where I have a set of known keys for a map, but I would like to lazily defer the creation of the according value to the first request:

val treeMapByEpoch: MutableMap<String, TreeModel>  = mutableMapOf()
val allIds = listOf("a","b","c","d")
for (i in allIds) {
    // very expensive calculation:
     treeMapByEpoch.getOrPut(i, { expensiveBuild(i) })
}

Can I elegantly defer the expensive calculations of the values? I’m aware of delegated properties but for this I might miss some of Kotlin’s greatness…

Update: On looking again into the Map interface I realized that the interface is not very well suited for this requirement because of the Map.entries and Map.values methods.
But as a general puzzler: What would be a elegant solution here?

See https://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections4/map/LazyMap.html

2 Likes

@fvasco Thanks. Great pointer which indeed perfectly fits my requirement.