2

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

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
Suma
  • 33,181
  • 16
  • 123
  • 191
  • Does this answer your question? [Find synthetic members in class fields in Scala](https://stackoverflow.com/questions/20519347/find-synthetic-members-in-class-fields-in-scala) – talex Aug 22 '21 at 10:49
  • @talex I don't know what is enough for the OP but that answer relates to Java reflection in Scala, not to Scala reflection used in this question. – Dmytro Mitin Aug 22 '21 at 11:19
  • @talex I am afraid it does not. I have specifically written in my question the `isSynthetic` does not help (meaning it is false) for the superfluous field. – Suma Aug 22 '21 at 12:13
  • @Suma You and talex are talking about different `isSynthetic`. You are talking about `scala.reflect.api.Symbols.SymbolApi.isSynthetic` . He is talking about `java.lang.reflect.Field.isSynthetic`. – Dmytro Mitin Aug 23 '21 at 22:32
  • @DmytroMitin You are correct. I have tried the other `isSynthetic` now and there is still no difference. https://scastie.scala-lang.org/DWy801FsTvq2XKZwU8TVrw – Suma Aug 24 '21 at 06:16

0 Answers0