Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a solution to "Cannot access '<init>': it is private in XYZ?

Tags:

kotlin

I included a library I'd like to use, but in accessing to one of its classes I get the error message,

"Cannot access '<init>': it is private in [class name]

Is there something I can do to rectify this on my side, or am I just stuck to not use the package?

like image 627
JohnL Avatar asked Nov 21 '18 14:11

JohnL


3 Answers

The error means the constructor is private. Given your comment, I'm assuming you're using a library. If this is the case, you'll have to find a different way to initialize it. Some libraries have factories or builders for classes, so look up any applicable documentation (if it is a library or framework). Others also use the singleton pattern, or other forms of initialization where you, the developer, don't use the constructor directly.

If, however, it is your code, remove private from the constructor(s). If it's internal and you're trying to access it outside the module, remove internal. Remember, the default accessibility is public. Alternatively, you can use the builder pattern, factory pattern, or anything similar yourself if you want to keep the constructor private or internal.

like image 190
Zoe stands with Ukraine Avatar answered Oct 18 '22 02:10

Zoe stands with Ukraine


I came across this issue when trying to extend a sealed class in another file. Without seeing the library code it is hard to know if that is also what you are attempting to do.

The sealed classes have the following unique features:

  • A sealed class can have subclasses, but all of them must be declared in the same file as the sealed class itself.

  • A sealed class is abstract by itself, it cannot be instantiated directly and can have abstract members.

  • Sealed classes are not allowed to have non-private constructors (their constructors are private by default).

  • Classes that extend subclasses of a sealed class (indirect inheritors) can be placed anywhere, not necessarily in the same file.

For more info, have a read at https://www.ericdecanini.com/2019/10/14/kotlins-sealed-class-enums-on-steroids/

Hopefully, this will help others new to Kotlin who are also encountering this issue.

like image 23
RJ. Avatar answered Oct 18 '22 02:10

RJ.


Class constructors are package-private by default. Just add the public keyword before declaring the constructor.

like image 2
ddvader44 Avatar answered Oct 18 '22 01:10

ddvader44