Internal vs Protected Constructor to prevent free floating object creation

Hi Team,
I have started using Kotlin recently and finding myself bit comfortable with it, but lately with increasing complexity of our API design, I am finding some restriction with Kotlin which is making me nervous now.

I wanted to prevent some objects to be created by the end users directly outside package/module, and should be created only by other classes within the package, I was looking to make my constructor protected.
so these readonly objects should be available to end user outside package but not allowed to be created by end users directly.


A FileInfo object should only be created by a method called getFileInfo() within File object. so user should not be able to create FileInfo object himself.
once this object get created it should be available to the end user for other operation, or passing to some other objects.

this is very easy in java.

public class FileInfo {
       protected FileInfo(String fileName, String fileSize, String creationDate){

now lets talk about kotlin,
when I am making my FileInfo class to internal, I am getting error in a public function of an Interface which has return type of FileInfo (which has internal access modifier )

Please suggest! it looks like kotlin limitation to me.

I think what you are looking for is:

class FileInfo internal constructor(fileName: String, fileSize: String, creationDate: String) {
    // class stuff ...

This makes the class available to everybody but the constructor only to inside the module


This looks to be working, thanks for sharing this, I dont see any option to mark this as accepted answer, but liked your reply.