Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get object from Play cache (scala)

How to get object from Play cache (scala)

Code to set:

play.api.cache.Cache.set("mykey98",  new Product(98), 0)

Code to get:

val product1: Option[Any]  = play.api.cache.Cache.get("mykey98")

I get Option object. How to get actual Product object I stored in first step.

like image 277
user3067829 Avatar asked Feb 03 '26 18:02

user3067829


1 Answers

First and foremost, I would suggest using Cache.getAs, which takes a type parameter. That way you won't be stuck with Option[Any]. There are a few ways you can do this. In my example, I'll use String, but it will work the same with any other class. My preferred way is by pattern matching:

import play.api.cache.Cache

Cache.set("mykey", "cached string", 0)

val myString:String = Cache.getAs[String]("mykey") match {
    case Some(string) => string
    case None => SomeOtherClass.getNewString() // or other code to handle an expired key
}

This example is a bit over-simplified for pattern matching, but I think its a nicer method when needing to branch code based on the existence of a key. You could also use Cache.getOrElse:

val myString:String = Cache.getOrElse[String]("mykey") {
    SomeOtherClass.getNewString()
}

In your specific case, replace String with Product, then change the code to handle what will happen if the key does not exist (such as setting a default key).

like image 119
Michael Zajac Avatar answered Feb 05 '26 06:02

Michael Zajac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!