Is it possible to create extension constructors in

2019-04-19 19:45发布

问题:

In other languages like Swift, there is the possibility of creating a function extension that adds a new constructor.

Something like this:

// base class
class Whatever() {
    ...
}

// constructor method extension
fun Whatever.constructor(potato: String) {
    setPotato(potato)
}

fun main(args: Array<String>) {
    println(Whatever("holi"))
}

Are there any means to do this in Kotlin?

回答1:

Seems that there are not an official "function extension for constructors" but you can create a package-method that imitates a constructor

class Foo() {
    ...
}

fun Foo(stuff: Int): Foo = Foo().apply {setStuff(stuff)}

fun main(args: Array<String>){
    println(Foo(123))
}


回答2:

Not like in Swift, because:

Extensions are resolved statically. Extensions do not actually modify classes they extend. By defining an extension, you do not insert new members into a class, but merely make new functions callable with the dot-notation on variables of this type. (Source)


If a companion object is defined in your target class, go with s1m0nw1's approach. The advantage is that you can call the extension function without an instance (statically) of the target class.


If not, use a classic Factory Pattern:

class Fruit(var name: String = "") {
}

class FruitFactory {
    companion object {
        fun create(name: String): Fruit {
            return Fruit().apply {
                this.name = "Tasty $name"
            }
         }
    }
}

fun main(args: Array<String>) {
    val orange = Fruit("Orange")
    println(orange.name)

    val apple = FruitFactory.create("Apple")
    println(apple.name)
}

You can extend the Factory as you wish with further constructors either nested or as extension functions.

Output:

Orange
Tasty Apple



回答3:

You can't do this. What you can do though: Extend the companion object of a class with a factory method:

// base class
class Whatever() {
    companion object {

    }

}

// factory extension
fun Whatever.Companion.withPotato(potato: String) {
    //setPotato(potato)
}

fun main(args: Array<String>) {
    println(Whatever.withPotato("holi"))
}

The only problem: A companion object has to be existent to do this.



标签: kotlin