Is it possible to create extension constructors in Kotlin?

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

    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){
        println(Foo(123))
    }
    

提交回复
热议问题