Is it possible to create extension constructors in Kotlin?

后端 未结 5 844
滥情空心
滥情空心 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:05

    Based on @s1m0nw1 solution, I can adjust it to be more like the OP wanted by overriding operator invoke.

    // base class
    class Whatever() {
        companion object {
            fun setPotato(potato: String)
        }
    }
    
    operator fun Whatever.Companion.invoke(potato: String) {
        setPotato(potato)
    }
    
    fun main(args: Array) {
        println(Whatever("holi"))
    }
    

    Keep in mind that it still needs companion object inside base class. If you can't edit the source of base class (in case of kotlin framework class or third party class), and if it already has companion object that you want to add your new method to, you can always use an extension function:

    fun Int.Companion.setPotato(potato: String) {
        // ...
    }
    

提交回复
热议问题