scala - Retrieve typed stored values from Map -


i'd put data hashmap , retrieve these typed values using function. function takes expected type , default value in case value not stored in hashmap. type erasure of jvm makes tricky thing.

q: how can retrieve typed value?

code , results below.

abstract class parameters(val name: string) {   val parameters = new hashmap[string, any]()    def put(key: string, value: any) = parameters(key) = value    def get(key: string) = parameters.getorelse(key, none)    def remove(key: string) = parameters.remove(key)     def g0[t: typetag](key: string, defaultvalue: t) = {     get(key) match {       case x: t => x       case none => defaultvalue       case _ => defaultvalue     }   }     def g1[t: classtag](key: string, defaultvalue: t) = {     val compareclass = implicitly[classtag[t]].runtimeclass      get(key) match {       case none => defaultvalue       case x if compareclass.isinstance(x) => x.asinstanceof[t]     }   } }  class p extends parameters("aparmlist") {   put("1", 1)   put("3", "three")   put("4", 4.0)   put("width", 600)    println(g0[int]("width", -1))   println(g0[int]("fail", -2))   println(g1[int]("width", -3))   println(g1[int]("fail", -4)) }   object typematching {   def main(args: array[string]) {     new p   } } 

the output (comments in parenthesis): 600 (as expected) none (expected -2) , match error (java.lang.integer stored, int required)


Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -