I am using an API where a trait is given like this:
package pkg
trait Trait {
private[pkg] def f = ...
private[pkg] val content = ...
}
I would like to access the variable content and function f in my code, using the API from a Jar file (so I cannot modify the original code to remove the private definition).
What I was able to come up with as a first solution is to create a new bridge class in the same package, that helps me access the private/protected member functions like this:
package pkg
trait PkgBridge {
def f = Trait.f
def getContent(t : Trait) = t.content;
}
This way I can call the package private members from my code.
I was wondering if there is any sophisticated way or common pattern for this kind of situations (like some magic with implicits or something?).
Thanks!
What you are doing works, is probably as good a way to do it as any, and is discouraged.
If something is package private it is probably an implementation detail for which an interface has not be specified sufficiently well to risk exposing anyone to it or to allow it to be completely private. So be careful! There may be good reason to not do this.
Aside from reflection, the only way within Scala to get at package private content is to be in that package, so your method is an appropriate one.
Note that this alternative might be useful as well:
and then you can
to specifically pick up the extensions that you want to have access to (under alternate names).