Is there a solution to "Cannot access '<init>': it is private in XYZ? - 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?

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.

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.

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

By default constructor is public so need to remove internal keyword.

Related

What is the difference between sealed and internal in Kotlin?

What is the difference between sealed and internal in Kotlin? I have read Kotlin's documentation on sealed classes and visibility modifiers; however, it is still not clear to me when to use sealed vs. internal. Maybe someone could provide real-world code samples?
Sealed classes | Kotlin & Visibility modifiers | Kotlin resources.
sealed class will be visible in all modules, but extendable only in the same module. This means if you have this:
sealed class MyClass {} then you can do this in the same module:
class MyExtensionClass: MyClass() {}
But you can't do the same thing in another module. But you can still use both MyClass and MyExtensionClass in another module.
For example you can do this in another module:
val x: MyClass = MyExtensionClass()
You can't instantiate a sealed class directly neither in the same or another module. This means you can't do this nowhere:
val x = MyClass()
So sealed class is basically an abstract class which can only be implemented in the same module.
internal class can be used and extended in the same module just like a sealed class, but you can do neither in another module. So you can't even use or instantiate it in another module. Also you can directly instantiate an internal class as long as you are doing it in the same module.
So: Use sealed to better control extending something. For example you create a library and you want a class from this library to be used but not extended. Use internal if you wan't your class to be invisible to other modules (you create a library, but certain class in this library shouldn't even be directly compile time usable by libraries users)
A good use case for sealed class:
You build a library and have some abstract class or interface which has multiple different implementations, but you want to make sure the libraries user doesn't add its own implementations (you wan't to be in control of implementation details).
A good use case for internal class:
You have some interface and a factory that creates implementations, but you don't want the implementing class to be compile-time visible to libraries users. They just use the factory and don't need to worry about the implementation. They might build their own implementation though and therefor not use the factory you provided and this is OK.
These are not mutually exclusive. You can have an internal sealed class as well.
internal is about visibility, and sealed is about inheritance rules.
internal means the class type is only visible within the module. In other modules, you can't even mention the name of the type.
sealed means it is open (can be subclassed), but subclasses (or implementations if it's a sealed interface) can only be defined in the same module, and the compiler keeps track of an exhaustive list of all subclasses. Another rule is that you can't create anonymous subclasses of it (object: MySealedClass). The advantage of a sealed type is that the compiler knows when you've exhaustively checked a type in when statements, if/else chains, etc. It can also be used in a library to ensure that only known implementations of a class or interface are ever passed to it (prevent users from creating subclasses of something and passing them into the library).
Bonus:
Visibility modifier keywords: public, internal, private, protected
Inheritance modifier keywords: open, final, sealed
data and value also cause a class to be final implicitly as a side effect.

How Cloning Breaks singleton

1) Singleton means the class have one instance. Having private constructer. No way to create object except reflection. No subclassing.
If i want to clone my singleton classthen class must and should implement Cloneable and override clone() right.
am not going to implement Cloneable interface in my Singleton class.
Then how cloning breaks my singleton. is this correct. Please clarify some one. if am wrong.
what is the need of throwing clonenotsupported exception.
No reason to implement Cloneable and override clone() to throw CloneNotSupportedException. Object. Clone, throws expectation when the Cloneable interface is absent.
The correct way to create singleton class using enums can be referred in my favorite java book "Effective Java" . Please read that.

Proper use of private constructors

I was reading about private constructor and found a few points that I couldn't understand. It said, if you declare a constructor as private:
That class cannot be explicitly instantiated from another class
That class cannot be inherited
Should be used in classes containing only static utility methods
My first question: Point 2 says the class cannot be inherited. Well, if you declare a class private then it would still satisfy this property. Is it because, if a class is private, it can still be explicitly instantiated from outside by another class?
My second question: I don't understand point 3. If I have a helper class which is full of static methods, I would never have to instantiate that class to use the methods. So, what is the purpose of a constructor in that class which you are never going to instantiate?
Answer for Java
Question 1 You're confusing a private class, with a class that has a private constructor. Private constructors are used mainly for static classes that are not meant to be instatiated (i.e. they just have a bunch of static methods on them).
Question 2 Exactly there is no need for a constructor so you have to explicitly create a private constructor so that it does not get a default constructer that the JVM will provide if none is defined
An empty class with no methods defined will always be given a no argument constructor by the JVM by default
I take java and c++ as an examples (not the best OO languages known, but very popular) - since you are not defining which languge do you mean.
Ad.2. In these languages you must either call superclass constructor explicitly or it is implicitly called for you. From a subclass you cannot call private methods (only public and protected) - this rule applies to constructors as well. This means if the class has only private constructors, there is no way to call one in subclass constructor. So you cannot subclass such class.
Ad. 3. It is just to avoid confusion - since this class is only a container for utility methods, there is no point in instantiating it. This way you can enforce this rule at compile time.

adapter pattern and dependency

I have little doubt about adapter class. I know what's the goal of adapter class. And when should be used. My doubt is about class construction. I've checked some tutorials and all of them say that I should pass "Adaptee" class as a dependency to my "Adapter".
e.g.
Class SampleAdapter implements MyInterface
{
private AdapteeClass mInstance;
public SampleAdapter(AdapteeClass instance)
{
mInstance=instance;
}
}
This example is copied from wikipedia. As you can see AdapteeClass is passed to my object as dependency. The question is why? If I'm changing interface of an object It's obvious I'm going to use "new" interface and I won't need "old" one. Why I need to create instance of "old" class outside my adapter. Someone may say that I should use dependency injection so I can pass whatever I want, but this is adapter - I need to change interface of concrete class. Personally I think code bellow is better.
Class SampleAdapter implements MyInterface
{
private AdapteeClass mInstance;
public SampleAdapter()
{
mInstance= new AdapteeClass();
}
}
What is your opinion?
I would say that you should always avoid the new operator in a class when it comes to complex objects (except when the class is a Builder or Factory) to reduce coupling and make your code better testable. Off course objects like a List or Dictionary or value objects can be constructed inside a class method (which is probably the purpose of the class method!)
Lets say for example that your AdapteeClass is a Remote Proxy. If you want to use Unit Testing, your unit tests will have to use the real proxy class because there is no way to replace it in your unit tests.
If you use the first approach, you can easily inject a mock or fake into the constructor when running your unit test so you can test all code paths.
Google has a guide on writing testable code which describes this in more detail but some important points are:
Warning Signs for not testable code
new keyword in a constructor or at field declaration
Static method calls in a constructor or at field declaration
Anything more than field assignment in constructors
Object not fully initialized after the constructor finishes (watch out for initialize methods)
Control flow (conditional or looping logic) in a constructor
Code does complex object graph construction inside a constructor rather than using a factory or builder
Adding or using an initialization block
AdapteeClass can have one or more non-trivial constructors. In this case you'll need to duplicate all of them in your SampleAdapter constructor to have the same flexibility. Passing already constructed object is simpler.
I think creating the Adaptee inside the Adapter is limiting. What if some day you want to adapt a pre-existing instance?
To be honest though, I'd do both if at all possible.
Class SampleAdapter implements MyInterface
{
private AdapteeClass mInstance;
public SampleAdapter()
: base (new AdapteeClass())
{
}
public SampleAdapter(AdapteeClass instance)
{
mInstance=instance;
}
}
Let's assume you have an external hard drive with a regular USB port and you are trying to hook it up with a Mac which only has type-c ports. Yes, you can buy a new drive which has a type-c port but what about the data in it?
It's the same for the adapter pattern. There're times you initialize AdapteeClass with tons of flavors. When you do the conversion, you want to keep all the context.

Issue with MVVMLight ViewModelBase public parameterless constructor in inherited base class for WP7 Tombstoning

I am handling tombstoning in Wp7 by dumping my ViewModel into the PhoneApplicationService state (see this link for more info).
My ViewModel (VM) inherits from the MVVM Light Toolkit (ViewModelBase) which has a protected parameterless constructor only.
This causes the serilization to fail with:
"The type 'GalaSoft.MvvmLight.ViewModelBase' cannot be deserialized in partial trust because it does not have a public parameterless constructor."
Excuse my ignorance but serialization is new to me - I think I understand why it's failing, but I am trying to think of ways around it. For example, can I mark the entire base class as non-serilizable or ignored like I do certain fields in classes ([IgnoreDataMember])? I don't need to store anything that is in this class.
Is there anyway around this? I don't want to edit the source of that assembly to mark it public instead of protected.
Public default constructors in abstract classes are frowned upon by StyleCop, which is why I made the ViewModelBase one protected. As you found out, this however causes issues with serialization. This issue is more acute in WP7 where it is tempting to dump the whole vm in serialization for safe keeping.
Right now, the only fix I can propose is to implement your own viewmodelbase class. I will consider changing the constructor to public in a future release.
Cheers,
Laurent