dimanche 25 octobre 2020

Why is a type of the member of the object different in a function?

Code below produces following result:

as member: nested : AnyRef{def x: Int; def x_=(x$1: Int): Unit}
as local: nested: Object

(Tested with Scala 2.12.12 and Scala 2.12.3)

Can someone explain why?

object Main extends App {

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

    for {
      symbol <- currentMirror.classSymbol(m.getClass).toType.members
      if symbol.isTerm && !symbol.isMethod && !symbol.isModule
    } yield {
      s"{symbol.name.decodedName}: ${symbol.info}"
    }
  }

  object obj {
    var nested = new {
      var x = 0
    }
  }

  getNestedType(obj).foreach(x => println(s"as member: $x"))


  def f(): Unit = {
    object obj {
      var nested = new {
        var x = 0
      }
    }

    getNestedType(obj).foreach(x => println(s"as local: $x"))
  }

  f()

}




Aucun commentaire:

Enregistrer un commentaire