0

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.

  • Why not just assign `callback` to a `lazy val` and then use that `val`? – Tim Jan 14 '22 at 10:18
  • I would add logs to see where it is evaluated, you have `.getOrElse(callback)` twice, so if there was something wrong with cache itself you'd still get result but not from where you wanted. – Mateusz Kubuszok Jan 14 '22 at 16:20
  • Can you explain why you want the argument to be `lazy`? This will cause it to be evaluated every time which appears to be the opposite of what you want. When exactly do you want `callback` to be evaluated? – Tim Jan 15 '22 at 07:44

0 Answers0