Is it possible to create extension constructors in Kotlin?

后端 未结 5 819
滥情空心
滥情空心 2021-01-03 18:45

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

Something like this:

// base c         


        
5条回答
  •  清酒与你
    2021-01-03 19:08

    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) {
        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

提交回复
热议问题