https://kotlinlang.org logo
#announcements
Title
# announcements
r

Ruckus

04/11/2018, 6:12 PM
You can do that. Some other options are to throw the factory functions in the companion object, have multiple constructors on the class, or just use default parameters:
Copy code
class Example1 private constructor(val a: Int, val b: String) {
    companion object {
        fun factory1(a: Int) = Example1(a, "N/A")
        fun factory2(b: String) = Example1(-1, b)
    }
}

// Example1.factory1(17)
// Example1.factory2("Fred")

class Example2 private constructor(val a: Int, val b: String) {
    constructor(a: Int) : this(a, "N/A")
    constructor(b: String) : this(-1, b)
}

// Example2(17)
// Example2("Fred")

class Example3(val a: Int = -1, val b: String = "N/A")

// Example3(a = 17)
// Example3(b = "Fred")