Created
February 21, 2012 11:06
-
-
Save kenbot/1875884 to your computer and use it in GitHub Desktop.
Drew example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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