Skip to content

Instantly share code, notes, and snippets.

@kenbot
Created February 21, 2012 11:06
Show Gist options
  • Save kenbot/1875884 to your computer and use it in GitHub Desktop.
Save kenbot/1875884 to your computer and use it in GitHub Desktop.
Drew example
import scala.collection.Map
import scala.sys.error
import java.util.TimeZone
import scala.reflect.Manifest
class FieldMapping[V, P: Manifest](val code: Int, val toPrimitive: V => P, val fromPrimitive: P => V) {
type PrimitiveMap = Map[Int, Any]
def this(code: Int) = this(code, _.asInstanceOf[P], _.asInstanceOf[V])
def get(map: PrimitiveMap): Option[V] = map.get(code) match {
case Some(p: P) => Some(fromPrimitive(p))
case Some(x) => error("Expected primitive of type " + manifest[P] + " but found " + x.getClass + " for code " + code)
case None => None
}
def put(map: PrimitiveMap, value: Option[V]): PrimitiveMap = {
val newPair = value.map(v => code -> toPrimitive(v))
map ++ newPair
}
}
object FieldMapping extends App {
val timeZone = TimeZone.getTimeZone("UTC")
val field = new FieldMapping[TimeZone, String](11, _.getID, id => TimeZone.getTimeZone(id))
val primitive = field.toPrimitive(timeZone)
val value = field.fromPrimitive(primitive)
println(primitive.getClass + " : " + primitive)
println(value.getClass + " : " + value)
val emptyMap = Map.empty[Int, Any]
val map = field.put(emptyMap, Some(timeZone))
println(map)
println(field get map)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment