163

How do I declare a secondary constructor in Kotlin?

Is there any documentation about that?

Following does not compile...

class C(a : Int) {
  // Secondary constructor
  this(s : String) : this(s.length) { ... }
}
ironic
  • 8,368
  • 7
  • 35
  • 44

13 Answers13

125

Update: Since M11 (0.11.*) Kotlin supports secondary constructors.


For now Kotlin supports only primary constructors (secondary constructors may be supported later).

Most use cases for secondary constructors are solved by one of the techniques below:

Technique 1. (solves your case) Define a factory method next to your class

fun C(s: String) = C(s.length)
class C(a: Int) { ... }

usage:

val c1 = C(1) // constructor
val c2 = C("str") // factory method

Technique 2. (may also be useful) Define default values for parameters

class C(name: String? = null) {...}

usage:

val c1 = C("foo") // parameter passed explicitly
val c2 = C() // default value used

Note that default values work for any function, not only for constructors

Technique 3. (when you need encapsulation) Use a factory method defined in a companion object

Sometimes you want your constructor private and only a factory method available to clients. For now this is only possible with a factory method defined in a companion object:

class C private (s: Int) {
    companion object {
        fun new(s: String) = C(s.length)
    }
}

usage:

val c = C.new("foo")
Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
Andrey Breslav
  • 24,795
  • 10
  • 66
  • 61
  • 25
    If secondary constructors are never supported, primary constructors should be renamed. ;) – Scooter Feb 17 '14 at 11:00
  • 3
    Andrey Breslav, I believe it was a bad idea to drop support for secondary constructors in Kotlin since these constructors are necessary sometimes, especially when working with Java frameworks and extending Java classes. Hope you'll get them back soon. – Michael Jul 17 '14 at 07:46
  • 2
    That's funny: secondary constructors returned back :) – ruX Apr 13 '15 at 18:07
  • 2
    Secondary constructors were added in M11. – Jayson Minard Dec 25 '15 at 15:56
  • Is it still considered best practice to use static factory methods as described in Effective Java? Or is it not as necessary now? I imagine you will always want to use static factories if you ever foresee a need to control instances. – tmn Jan 08 '16 at 03:57
  • @ThomasN. You are really asking a new question, disguised as a comment. Regardless, this is subjective. Factories help when there is logic needed to assemble the class and you want to make that easier. Or when it is dangerous to directly set values of the class in the constructor. But I wouldn't call it a "best practice" for Kotlin. "It depends" and is very opinionated answer. I think this would be downvoted as a question because it isn't specific, no use case. If you have a specific use case in mind, and you don't feel right about it being a constructor, ask that as a question. – Jayson Minard Jan 12 '16 at 00:46
  • "class object" has been renamed "companion object", as of M12. https://blog.jetbrains.com/kotlin/2015/05/kotlin-m12-is-out/ – Ari Lacenski Jun 12 '17 at 21:56
63

As the documentation points, you can use a secondary constructor this way

class GoogleMapsRestApiClient constructor(val baseUrl: String) {

    constructor() : this("https://api.whatever.com/")

}

Remember that you must extended the first constructor behavior.

Marcin Koziński
  • 10,835
  • 3
  • 47
  • 61
cesards
  • 15,882
  • 11
  • 70
  • 65
  • 1
    Instead of extending first constructor directly from the second one can delegate to another secondary constructor, that already does it: – Picrochole Jun 06 '17 at 06:20
  • 1
    I think this one is better for current case: ` class GoogleMapsRestApiClient constructor(val baseUrl: String = "https://api.whatever.com/") { //class body } ` – Alexander Krol Feb 13 '18 at 10:27
  • It is! But that's not the context of the problem ^^ I could edi it with a better suggestion if you have one. Thanks for the shout out @AlexanderKrol – cesards Feb 15 '18 at 12:11
31

for declaring a secondary constructor Kotlin just use the constructor keyword: like

this is a primary constructor:

class Person constructor(firstName: String) {

}

or

class Person(firstName: String) {

}

for the secondary constructor code like this:

class Person(val name: String) {
    constructor(name: String, parent: Person) : this(name) {
        parent.children.add(this)
    }
}

it is mandatory to call the primary constructor otherwise, the compiler will throw the following error

Primary constructor call expected
Rashid Iqbal
  • 840
  • 10
  • 14
16

Constructors with init:

class PhoneWatcher : TextWatcher {

    private val editText: EditText
    private val mask: String

    private var variable1: Boolean = false
    private var variable2: Boolean = false

    init {
        variable1 = false
        variable2 = false
    }

    constructor(editText: EditText) : this(editText, "##-###-###-####")

    constructor(editText: EditText, mask: String) {
        this.editText = editText
        this.mask = mask
    }
    ...
}
CoolMind
  • 26,736
  • 15
  • 188
  • 224
10

Too late to answer, but here is my humble contribution:)

As Kotlin supports default param value, (note: I want to use power of null) like this:

data class MyClass(val a: Int? = null, val b: String? = null, val c: Double? = null)

we dont need to have multiple constructor. but even if we want it, we can do it this way as well:

data class MyClass(val a: Int?, val b: String?, val c: Double?){
    constructor() : this(null,null,null)
    constructor(a : Int) : this(a,null,null)
    constructor(a : Int, b: String) : this(a,b,null)
}

we can instantiate this class in following ways:

println(MyClass().toString())
println(MyClass(1).toString())
println(MyClass(1,"String").toString())
println(MyClass(1,"String",0.5).toString())

and lets see the result as well:

enter image description here

Palak Darji
  • 1,084
  • 18
  • 28
10

Custom View Example with Multiple Constructors in Android:

class ShaderBackground : View {


    constructor(context: Context) : super(context) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        init()
    }

    private fun init() {

       // Init stuff here
        paint = Paint();
        paint.strokeWidth = 10f;
        paint.style = Paint.Style.FILL_AND_STROKE;

    }
Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154
  • Any shortcut for making constructor for korlin files i tried ALT+INSERT but not showing any menu for generating constructor. **can you please share the shortcut for generate constructor for kotlin POJO?** – Arbaz.in Apr 29 '20 at 06:00
  • @Arbaz.in Generate a constructor for a class On the Code menu, click Generate ⌘N. In the Generate popup, click Constructor for Kotlin. If the class contains fields, select the fields to be initialized by the constructor and click OK. – Joel Jul 17 '21 at 01:56
7

You can define multiple constructors in Kotlin with constructor but you need to skip default constructor class AuthLog(_data: String)

class AuthLog {

    constructor(_data: String): this(_data, -1)

    constructor(_numberOfData: Int): this("From count ", _numberOfData)

    private constructor(_data: String, _numberOfData: Int)

}

For more details see here

Update

Now you can define default constructor

class AuthLog(_data: String, _numberOfData: Int) {

    constructor(_data: String): this(_data, -1) {
        //TODO: Add some code here if you want
    }

    constructor(_numberOfData: Int): this("From count", _numberOfData)

}
4

I just saw this question and I think there may be another technique which sounds even better than those proposed by Andrey.

class C(a: Int) {
    class object {
        fun invoke(name: String) = C(name.length)
    }        
}

That you can either write something like val c:C = C(3) or val c:C = C("abc"), because the invoke methods work kind of the same way the apply methods work in Scala.

Update

As of now, secondary constructors are already part of the language spec so this workaround shouldn't be used.

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
caeus
  • 3,084
  • 1
  • 22
  • 36
  • Secondary constructors (since M11) are better than this option. – Jayson Minard Dec 25 '15 at 15:57
  • I answered this before the release of M11, it's quite mean to downvote it, why don't you just try to edit the answer? – caeus Jan 11 '16 at 21:33
  • I can't edit the answer because my edit would not be inline with your answer. I disagree that this should ever be suggested at all. Deleting your answer would prevent my downvote. – Jayson Minard Jan 12 '16 at 00:33
  • Maybe it was a useful hack prior to M11 but it isn't now, and shouldn't be here. If you leave it, you invite newer downvotes. Keep your old posts updated and you won't run into this. http://meta.stackexchange.com/a/121351/312466 – Jayson Minard Jan 12 '16 at 00:42
2

The code snippet below should work

class  C(a:Int){
  constructor(s:String):this(s.length){..}
}
Sachini Samarasinghe
  • 1,081
  • 16
  • 18
1
class Person(val name: String) {
    constructor(name: String, parent: Person) : this(name) {
        parent.children.add(this)
    }
}

you can try this.

Ruhul
  • 59
  • 1
  • 5
1

kotlin Secondary constructor example

class Person(name: String){
    var name=""
    var age=0

    constructor(age :Int,name : String)  : this(name){
        this.age=age
        this.name=name
    }
    fun display(){
        print("Kotlin Secondary constructor $name  , $age")
    }
}

main function

fun main(args : Array<String>){

    var objd=Person(25,"Deven")
    objd.display()
}
Deven Mer
  • 145
  • 1
  • 7
1

I was a bit confused with most of the answers. To make it easy to understand I am adding an example with more elements :

   @JsonInclude(JsonInclude.Include.NON_NULL)
   data class Response(val code: String) {
      var description: String? = null
      var value: String? = null

      constructor(code: String, description: String?) : this(code) {
          this.description = description
      }

      constructor(code: String, description: String?, value: String) : this(code, description) {
          this.value = value
      }
   }
Abbin Varghese
  • 2,422
  • 5
  • 28
  • 42
0

Use the variable 'internal' and then you can add multiple constructors inside single class like below. This will work flawlessly.

class AuthModel {
    var code: String? = null

    internal constructor(code: String?) {
        this.code = code
    }

    internal constructor() {}
}
bric3
  • 40,072
  • 9
  • 91
  • 111
Harish Reddy
  • 922
  • 10
  • 20