i trying check if field exists in generic class.
import scala.reflect.runtime.{universe => ru} class example[t:ru.typetag](val value:t) object example { def apply[t:ru.typetag](value:t, fieldname: string) : example[t] = { val t = ru.typeof[t] val hasfield: boolean = ??? // how can check class t has field name fieldname? if(hasfield) new example(value) else throw new runtimeexception() } } case class foo(field:string) object test{ example(foo("hola"), "field") // work example(foo("hola"), "other") // throws exception }
how can implement this??
scala 2.10:
val hasfield = t.declarations.exists { _.name.decodedname.tostring == fieldname }
scala 2.11:
val hasfield = t.decls.exists { _.name.decodedname.tostring == fieldname }
edit: didn't notice scala 2.10 requirement @ first
Comments
Post a Comment