I am adding caching in my scala code and using ScalaCache. I liked memoization in which you basically call function from inside of memoization. What I want is, I want to write a generic function withCache which accept other function like lazy arguments and want to call that to the memoization body. I tried as follow but it did not work
import scalacache.{Cache, _}
import scalacache.redis._
import scalacache.serialization.binary._
import _root_.redis.clients.jedis._
import scalacache.memoization.memoize
import scalacache.modes.try_.mode
import scala.concurrent.duration.DurationInt
import scala.util.Try
object LearningMemoization extends App {
val jedisPool = new JedisPool("localhost", 6379)
implicit val customisedRedisCache: Cache[String] = RedisCache(jedisPool)
def getStringById(id:Int) = s"Hi there I am $id"
def withCache[A](callback: => A)(implicit cache:Cache[A]):A = Try{
memoize[Try, A](Some(20.seconds)) {
callback
}.getOrElse(callback)
}.getOrElse(callback)
println(withCache(getStringById(5)))
}
What I am expecting is after calling println(withCache(getStringById(5)))
It should cache Hi there I am $id
for 20 seconds though I change the content from getStringById(id:Int)
method but It did not.. Basically what I want is getStringById(5) called when callback is declared.