Is it possible to create extension constructors in Kotlin?

In other languages, such as Swift, it is possible to create a function extension that adds a new constructor.

Something like that:

// base class class Whatever() { ... } // constructor method extension fun Whatever.constructor(potato: String) { setPotato(potato) } fun main(args: Array<String>) { println(Whatever("holi")) } 

Are there any funds for this in Kotlin?

+5
source share
3 answers

There doesn't seem to be an official β€œextension of functions for constructors", but you can create a batch method that mimics the constructor

 class Foo() { ... } fun Foo(stuff: Int): Foo = Foo().apply {setStuff(stuff)} fun main(args: Array<String>){ println(Foo(123)) } 
+10
source

Not like Swift because:

Extensions are allowed statically. Extensions do not actually change the classes that they extend. By defining extensions, you do not insert new members into the class, but simply make new functions called using the dot notation for type variables. ( Source )


If a companion object is defined in your target class, go with the s1m0nw1 approach. The advantage is that you can call the extension function without an instance of the (statically) target class.


If not , use the 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<String>) { val orange = Fruit("Orange") println(orange.name) val apple = FruitFactory.create("Apple") println(apple.name) } 

You can expand Factory as you wish with additional constructors, either nested or as extension functions.

Output:

Orange
Tasty apple

+6
source

You cannot do this. What you can do: Extend the companion object of the class with the factory method:

 // base class class Whatever() { companion object { } } // factory extension fun Whatever.Companion.withPotato(potato: String) { //setPotato(potato) } fun main(args: Array<String>) { println(Whatever.withPotato("holi")) } 

The only problem: a companion object must exist for this.

+4
source

Source: https://habr.com/ru/post/1272361/


All Articles