public
Created

  • Download Gist
gistfile1.scala
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
import java.util.TimeZone
import scala.collection.mutable.HashMap
 
class FieldMapping[V, P](val code: Int, val primitiveType: Class[P], val valueType: Class[V], val toPrimitive: (V => P), val fromPrimitive: (P => V)) {
 
def this(code: Int, primitiveType: Class[P], valueType: Class[V]) {
this(code, primitiveType, valueType, (t => t.asInstanceOf[P]), (v => v.asInstanceOf[V]))
}
 
def get(map: scala.collection.Map[Int, _]): Option[V] = {
val option = map.get(code)
if (option.isEmpty) {
None
}
 
val primitive = option.get
if (primitive == null) {
None
}
 
if (primitive.getClass() != primitiveType) {
throw new ClassCastException("expected primitive of type " + primitiveType + " but found " + primitive.getClass() + " for code " + code)
}
 
Some(fromPrimitive(primitive.asInstanceOf[P]))
}
 
def put(map: scala.collection.mutable.Map[Int, Any], value: V) {
if (value != null) {
map.put(code, toPrimitive(value))
}
}
 
def put(map: scala.collection.mutable.Map[Int, Any], value: Option[V]) {
if (value != null && value.isDefined) {
map.put(code, toPrimitive(value.get))
}
}
 
}
 
object FieldMapping {
 
def apply[V, P](code: Int, primitiveType: Class[P], valueType: Class[V])(toPrimitive: (V => P))(fromPrimitive: (P => V)): FieldMapping[V, P] = {
new FieldMapping[V, P](code, primitiveType, valueType, toPrimitive, fromPrimitive)
}
 
def main(args: Array[String]) {
val timeZone = TimeZone.getTimeZone("UTC")
val field = FieldMapping[TimeZone, String](11, classOf[String], classOf[TimeZone])(timeZone => timeZone.getID())(id => TimeZone.getTimeZone(id))
 
val primitive = field.toPrimitive(timeZone)
val value = field.fromPrimitive(primitive)
println(primitive.getClass() + " : " + primitive)
println(value.getClass() + " : " + value)
 
val map = new HashMap[Int, Any]
field.put(map, timeZone)
println(map)
println(field.get(map))
}
 
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.