In other languages like Swift, there is the possibility of creating a function extension that adds a new constructor.
Something like this:
// 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 means to do this in Kotlin?
For doing this we create an extension function for MutableList<> with swap() function. The list object call the extension function (MutableList<Int>. swap(index1: Int, index2: Int):MutableList<Int>) using list. swap(0,2) function call.
In Kotlin, a class can also contain one or more secondary constructors. They are created using constructor keyword. Secondary constructors are not that common in Kotlin.
To do so you need to declare a secondary constructor using the constructor keyword. If you want to use some property inside the secondary constructor, then declare the property inside the class and use it in the secondary constructor. By doing so, the declared variable will not be accessed inside the init() block.
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<String>){ println(Foo(123)) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With