Saturday, 15 August 2015

to build a generic cast function in scala -



to build a generic cast function in scala -

i'd build function read settings properties file, key/value pairs, , cast expected types. if given field name does't exist, default value of specific t. doable?

i set pseudo code here , know how write real code help of scala reflection.

def getfield[t](fieldname: string): t = { val value = getfield(fieldname) if (value == null) { t match { case int => 0 case boolean => false ... case _ => null } } else value.asinstanceof[t] }

alternatively, throw exception if field not locate, not bad thought me... def getfield[t](fieldname: string): t = { val value = getfield(fieldname)

if (value == null) { throw new exception("error msg") } } else value.asinstanceof[t] }

i know how if returns option[t] (as discussed here writing generic cast function scala ).

i utilize implicit parameter pass default value. give 100% type safety + easy way override defaults not simple type, other types.

trait defaultvalue[t] { def default: t } object defaultvalue { def apply[t](value: t) = new defaultvalue[t] { val default: t = value } } trait lowleveldefaultimplicits { implicit val intdefaultvalue = defaultvalue[int](0) implicit val booleandefaultvalue = defaultvalue[boolean](false) } object mydefaults extends lowleveldefaultimplicits { // easy override defaults implicit val truebydefault = defaultvalue[boolean](true) } import mydefaults._ def readfield(s: string): = ... extern service phone call ... def getfield[t: defaultvalue](fieldname: string): t = { val value = readfield(fieldname) if (value == null) implicitly[defaultvalue[t]].default else value.asinstanceof[t] } println(getfield[int]("aaa")) println(getfield[boolean]("aaa"))

result:

0 true

^ - can see default "false" overridden higher priority implicit.

one drawback - need define defaults types t. think it's benefit. providing defaults each type rid of 'null' values.

scala generics reflection

No comments:

Post a Comment