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?