Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create extension constructors in Kotlin?

Tags:

kotlin

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?

like image 491
Aracem Avatar asked Oct 05 '17 09:10

Aracem


People also ask

How do I create a Kotlin extension?

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.

Can we have secondary constructor in Kotlin?

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.

How do I create a secondary constructor 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.


1 Answers

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)) } 
like image 134
Aracem Avatar answered Sep 19 '22 20:09

Aracem