Is it possible to create extension constructors in Kotlin?

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

    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) {
        println(Whatever.withPotato("holi"))
    }
    

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

提交回复
热议问题