dimanche 22 août 2021

How to recognize an outer variable which is listed between members by reflection?

I have a function which constructs a map by reflection from an object literal (the purpose is to make porting some JavaScript code easier). The function works fine, but I have found a case in which the reflections lists variables from an enclosing scope between members:

def mapFromObject[T](m: Any): Map[String, T] = {
  import scala.reflect.runtime.currentMirror

def listMembers(m: Any) = {
  import scala.reflect.runtime.currentMirror

  val anyMirror = currentMirror.reflect(m)
  val items = for {
    symbol <- currentMirror.classSymbol(m.getClass).toType.members
    if symbol.isTerm && !symbol.isMethod && !symbol.isModule
  } yield {
    val field = anyMirror.reflectField(symbol.asTerm)
    symbol.name.decodedName.toString
  }
  items
}


def convertLiteral() = {
  val par_some = ""
  val literal = new {
    var item = new {}
    var item2 = new {
      var value = par_some
    }
  }
  println(listMembers(literal))
}

convertLiteral()

I expect to get result item, item2, but I get par_some$1, item2, item instead.

Why is par_some$1 listed as a member of the class?

How can I check for such member, so that I can ignore it? I have tried various methods of Symbol, including isSynthetic and isImplementationArtifact, but nothing I have tried seems to be different from normal members.

Scastie repro: https://scastie.scala-lang.org/uiv4DBIERIKnZaiViZ0Aaw





Aucun commentaire:

Enregistrer un commentaire