Brainstorming: I am working on a Scala project where we do service calls and need to cache the return values using memcache. I was working on a Python project that used decorators to annotate the functions whose return values should be cached. I am looking for a similar way in Scala to add a caching aspect to a function.
Lets say I have this function def callingService(arg1: String, arg2: Int): String I want to
Any code that invokes callingService should not know about caching. The implementation of callingService should just call service X and return a String value and not deal with caching stuff.
I prefer Stackable Trait Pattern and Cake Pattern for that:
class Service {
def callingService(arg1: String, arg2: Int): String = "ok"
}
trait Memo[K, V] {
def cache(k: K)(v : => V): V
}
trait ServiceCache extends Service {
self : Memo[(String, Int), String] =>
abstract override def callingService(arg1: String, arg2: Int): String =
cache((arg1, arg2)) { super.callingService(arg1, arg2) }
}
trait MapCache[K, V] extends Memo[K, V] {
private val _cache = new collection.mutable.HashMap[K, V]
def cache(k: K)(v : => V): V = _cache.getOrElseUpdate(k, v)
}
using example:
val service = new Service with ServiceCache with MapCache[(String, Int), String]
and of course you can implement own Caching strategy and mix with it at the moment of service creation
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