0

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

Abdul Rahman
  • 1,294
  • 22
  • 41
  • 1
    i assume you mean `private [somepackage] class A`? – joel Jul 26 '18 at 15:25
  • You can write your own code in `somepackage` to access `A` and make it public to allow it being accessed from your main package. But note that this will run into trouble once Scala works with Java 9 module system. – Alexey Romanov Jul 26 '18 at 15:57

2 Answers2

1

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

joel
  • 6,359
  • 2
  • 30
  • 55
1

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

Jagat
  • 1,392
  • 2
  • 15
  • 25