I'm looking to cache information in a Map so I don't have to keep, for example, hitting a DB. In Java I'd use Google collection's excellent MapMaker and set an expiry, to keep the cache as fresh as necessary, and softValues, to keep the memory usage down. Then I'd have a function that computes the value for a key that currently isn't cached.
MapMaker().softValues
.expireAfterWrite(10, TimeUnit.MINUTES)
.makeComputingMap(Function(...));
What's the best way to do this in Scala?
As Kim said, why do it differently if MapMaker
works well for you?
import collection.JavaConverters._
val cache = /* your MapMaker code creating a Java map */.asScala
And now you access the underlying Java map with the methods from a Scala map.
I have created a functionally transparent expiration map in Scala. Adding and removing elements gives a new map, which also removes any expired values.
Expiration Map
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With