Skip to content

Instantly share code, notes, and snippets.

@nelanka
Last active August 29, 2015 14:20
Show Gist options
  • Save nelanka/ed0ac2cb7dad2a48b073 to your computer and use it in GitHub Desktop.
Save nelanka/ed0ac2cb7dad2a48b073 to your computer and use it in GitHub Desktop.
Proxy a cache that only uses String key and values
import java.util.concurrent.ConcurrentHashMap
trait StringDeserializer[T] {
def deserialize(s: String): T
}
trait StringSerializable[T] {
def serialize: String
}
class CacheProxy[K <: StringSerializable[K], V <: StringSerializable[V]]
(cache: ConcurrentHashMap[String, String])(implicit d: StringDeserializer[V]) {
def put(key: K, value: V) = cache.put(key.serialize, value.serialize)
def get(key: K): Option[V] = Option(cache.get(key.serialize)).map(d.deserialize)
}
case class Name(firstName: String, lastName: String) extends StringSerializable[Name] {
override def serialize: String = s"$firstName${NameDeserializer.delimiter}$lastName"
}
case class ContactInfo(phoneNumber: String, email: String) extends StringSerializable[ContactInfo] {
override def serialize: String = s"$phoneNumber${ContactInfoDeserializer.delimiter}$email"
}
implicit object NameDeserializer extends StringDeserializer[Name] {
val delimiter = '#'
override def deserialize(s: String): Name = {
val Array(firstName, lastName) = s.split(delimiter)
Name(firstName, lastName)
}
}
implicit object ContactInfoDeserializer extends StringDeserializer[ContactInfo] {
val delimiter = '#'
override def deserialize(s: String): ContactInfo = {
val Array(phoneNumber, email) = s.split(delimiter)
ContactInfo(phoneNumber, email)
}
}
val cache = new ConcurrentHashMap[String, String]()
val proxy = new CacheProxy[Name, ContactInfo](cache)
proxy.put(Name("James", "Kirk"), ContactInfo("917-123-4567", "james.kirk@enterprise.sf"))
println(proxy.get(Name("James", "Kirk")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment