mercredi 8 juillet 2015

Scala: Accessing package visible methods through structural types outside the package

This does not work as expected (since I am trying to call a package private run from outside Services):

object Services {
 class HelloPrinter {
   private[Services] def run = "Hello"
  }  
}

val obj = new Services.HelloPrinter

But, surprisingly this works:

val obj: {def run: String} = new Services.HelloPrinter
obj.run

I would say, its a bug in the compiler since as HelloPrinter does not match the structural type because of package visibility rules, it should not compile at all!

Here is a case where the program compiles but it throws a runtime exception (java.lang.NoSuchMethodException):

class HelloPrinter {
  private[HelloPrinter] def run = "Hello"
}  

val obj: {def run: String} = new HelloPrinter
obj.run

Is this a language feature or rule I am missing or legitimately a bug in Scala?





Aucun commentaire:

Enregistrer un commentaire