Skip to content

Anonymous classes methods becoming private when compiled. #9487

Closed as not planned
@scabug

Description

@scabug

When a type of an anonymous class is less specific that the definition of the class (AnyRef for example) the anonymous class methods become private. This happens with val, def and var definition inside the class.

  type T = {val x: String; def y: String; var z: String}

  // This one generates to compile the anonymous class properly.
  // It marks all methods and field accessors as private
  // If the return type is T then it compiles correctly
  def get(): AnyRef = new { val x = "x"; def y = "y"; var z = "z"}

  val obj = get()
  // Prints: Failure(java.lang.NoSuchMethodException: A$$anon$2.x())
  println(Try(obj.asInstanceOf[T].x))

  // Prints: Failure(java.lang.NoSuchMethodException: A$$anon$2.y())
  println(Try(obj.asInstanceOf[T].y))

  // Prints: Failure(java.lang.NoSuchMethodException: A$$anon$2.z())
  println(Try(obj.asInstanceOf[T].z))
  // Failure(java.lang.NoSuchMethodException: A$$anon$1.z_$eq(java.lang.String))
  println(Try(obj.asInstanceOf[T].z = "zz"))
  // Prints: Failure(java.lang.NoSuchMethodException: A$$anon$2.z())
  println(Try(obj.asInstanceOf[T].z))

  println
  println("Fields:")
  // Lists x and z fields as expected
  obj.getClass.getDeclaredFields.foreach(x => println(s"  $x"))
  println("Methods:")
  // All methods are private but should be public
  obj.getClass.getDeclaredMethods.foreach(x => println(s"  $x"))

It looks like a code pattern that should be avoided, but in Scala.js this is used to create javascript objects. scala-js/scala-js#1899

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions