I’m creating a simple cache trait (to cache my functions easily):
trait Cache[A,B] {
def _calc(v:A):B
private var cache = Map[A,B]()
def calc(v:A):B = {
cache.get(v) match {
case Some(x) => x
case None =>
val x = _calc(v)
cache += (v -> x)
x
}
}
}
The usage:
object Sol extends Cache[Int,Int] {
def _calc(v:Int):Int = { /* do something here */ }
}
Sol.calc(5)
It works properly, but the problem arises when I need to cache functions with more arguments – so I need to develop traits Cache2, Cache3, all copy-pasting code from the first trait.
The possible workaround is to convert functions with multiple arguments to functions accepting a tuple, but that does not seem right.
Is there a way to do it more generally and to avoid DRY principle violation?
You could at least automatically tuple your functions so that you can define the real function (for example
add) accepting a usual parameter list:Call it via
Add.calc(3, 5)Edit: Or use this way to implement Cache2 … CacheN without repeating the whole Cache code.
And again
and
Add2.calc(3, 5)