jeudi 9 mai 2019

In Scala, is it possible to get the val names from an object in declaration order?

I have several objects looking like this (number of val unknown, val names can be random):

object MyObj{
  val valAbc: ChainBuilder = a
  val valDef: ChainBuilder = b
  val valGhi: ChainBuilder = c
  val valAdb: ChainBuilder = d
  val val45: ChainBuilder = e
  ...
}

and I'd like to execute something like this, that puts the previous entry and it's value in a map, followed by the current entry, starting the second entry:

obj MyObjManager{
  def sortInMap(myObj: Object): Map[String, (ChainBuilder, String)] = {
    var myMap = mutable.Map.empty[String, (ChainBuilder, String)]
    var currentName: String = ""
    val listVals = :myObj.getClass.getDeclaredFields
    listVals.foreach{f =>
      if((current != "") && (f.getName!="MODULE$")){
        myMap.put(currentName,(myObj.getClass.getMethod(currentName).invoke(myObj), f.getName)
        current = f.getName
      }
    }
    myMap.toMap
  }
}

My issue is, MyObj.getClass.getDeclaredFields is not granted to take my vals in declaration order which is essential in my case.

Is there any way to do this in scala, maybe using scala.reflect.runtime.universe._ , that can assure the declaration order will be respected?

Thanks a lot





Aucun commentaire:

Enregistrer un commentaire