Is it possible to extend a package private class defined in a 3rd party jar in Scala

422 Views Asked by At

Is it possible to extend a package private class in scala that is defined in a 3rd party jar. So for instance if a 3rd party jar that my code depends on has some class like so

private [somepackage] A {

}

can I somehow subclass this class in my code?

Thanks

2

There are 2 best solutions below

0
On BEST ANSWER

Not according to Programming in Scala 3rd Ed., paraphrased:

package a
package b {
  private[a] class B
}

all code outside the package a cannot access class B

Note that here, package b is in package a.

Curiously, this doesn't appear to be the case in the REPL: see this post

0
On

Nope, you can't do that.

If you need it to stub/mock it, consider using a proxy to access class A, and stub/mock that proxy class instead. E.g., if A.doStuff is what you want to mock/stub, and A.accessStuff is what you need in your code, create a class

class ADecorated(underlying: A) {
  def doStuff() {
    underlying.doStuff()
    // whatever I want to do
  }

  def accessStuff() {
    x = underlying.accessStuff()
    // do something else and return
  }
 // Any other method you want to use
}

Replace usage of A.createA with new ADecorated(A.createA()). ADecorated is what you work with now