How to have a class which can only be instantiated by another specific class
I want to have a class that can only be instantiated by another class. I know I have to make the constructor
private otherwise everyone can instantiate it.
class Root private constructor() { } class RootMaker: Application() { fun createRoot() = Root() } // but this doesn't work because Root's constructor is private
one workaround is to make the maker
class, the inner class of the Root
class.
class Root private constructor() { class RootMaker: Application() { fun createRoot() = Root() } }
but I really don’t want to do this because the maker class is my application
class in android. so what is the better way?
If you want only one instance of an object you can use object
keyword in Kotlin. It implements Singleton
pattern:
class App : Application { val root = Root } object Root { fun createObject(): Any {} }
Now we can access to one instance of Root
class either by a property in App
class or via Root
class: Root.createObject()
UPDATE:
To implement a singleton that only one specific class has access to, we can use an interface and hide its implementation in that specific class (the maker class):
interface IRoot { // ... methods of creation different objects for dependency injection } class App : Application { val root: IRoot = Root // hide implementation of `IRoot` interface in `App` class private object Root : IRoot { // ... implementation of methods of creation different objects for dependency injection } }