private - Accessing parameters of the same name of different classes in Scala -
i have specific scenario, in have different abstract classes have child case classes can have different parameters, example:
abstract class ball() {} case class football(_name: string, _shape: string) extends ball case class basketball(_name: string, _size: int) extends ball
and different abstract class:
abstract class food() {} case class vegetarian(_name: string, calories: int) extends food case class meat(_name: string, proteincount: int) extends food
now, problem i'm facing need somehow extract name of of without knowing class is, know always, each class has parameters named _name
.
supposing have object
of of above classes, i'm trying this:
object.getclass.getdeclaredfield("_name").get(this)
but i'm getting error:
can not access member of class package.food modifiers "private"
i tried putting val , var before parameters in class doesnt help. tried doing "setaccessible(true)" in line before get(this), doesn't help.
the obvious clean solution have least common trait these classes:
trait hasname { def _name: string }
and can safely obj.asinstanceof[hasname]._name
. better yet if manage keep around static information obj
hasname
, in case obj._name
suffices.
if can't of that, reflection way go. can pretty using structural type, in case:
obj.asinstanceof[{ def _name: string }]._name
note slower above hasname
solution, , unchecked @ compile time.
Comments
Post a Comment