Kotlin - Factory Function for class with private constructor

In Kotlin, is it possible to have a factory function that instantiates a class with a private constructor?

My goal is to forcefully use the factory function that will be used, and to prevent instantiation through the class constructor.

Example:

// factory function, valid val myInstance = myClassOf() // class instantiation, invalid val myInstance = MyClass() 

I am trying to simulate the behavior of some built-in factory functions, such as intArrayOf() , for example.

 // works val myIntArray = intArrayOf() // not possible as IntArray has a private constructor val myIntArray = IntArray() 
+11
source share
3 answers

You can do something like this:

 import MyClass.Companion.myClassOf class MyClass private constructor() { companion object { fun myClassOf() = MyClass() } } //val myInstance1 = MyClass() // not allowed val myInstance2 = myClassOf() 
+7
source

You can use a companion object as follows:

 class MyClass private constructor() { companion object { operator fun invoke() = MyClass() } } val myInstance = MyClass() // Calls the factory function invoke() 

Name the factory function if it has special meaning. For instance:

 class MyClass private constructor(values: List<String>) { companion object { fun of(vararg values: String) = MyClass(values.toList()) } } val myInstance = MyClass.of("first", "second") 
+10
source

Try Builder instead.

 class FoodOrder private constructor( val bread: String?, val condiments: String?, val meat: String?, val fish: String?) { data class Builder( var bread: String? = null, var condiments: String? = null, var meat: String? = null, var fish: String? = null) { fun bread(bread: String) = apply { this.bread = bread } fun condiments(condiments: String) = apply { this.condiments = condiments } fun meat(meat: String) = apply { this.meat = meat } fun fish(fish: String) = apply { this.fish = fish } fun build() = FoodOrder(bread, condiments, meat, fish) } } 

Link: https://www.baeldung.com/kotlin-builder-pattern

+1
source

Source: https://habr.com/ru/post/1270553/


All Articles