Is it possible to create extension constructors in Kotlin?

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

    Another alternative is to just declare an extension function on the argument (or the first one if there are many):

    // base class
    class Whatever() {
        ...
    }
    
    // extension
    fun String.toWhatever() = Whatever().apply { setPotato(this) }
    
    fun main(args: Array) {
        println("holi".toWhatever())
    }
    

    The pros:

    • You avoid the hassle of declaring an empty Companion object
    • Still possible when the Whatever class doesn't have a Companion AND is not yours, so you couldn't add a Companion even if you wanted
    • Compact and idiomatic approach

提交回复
热议问题