0
votes

From the documentation I am trying to do something like this

//Primary:
class Main2Activity(val name: String) {

}

//Secondary:
constructor(a: Int) : super() {
   this.a = a
}

So the android studio gives me the option to create this secondary constructor . But it doesn't recognize the primary constructor which I wrote above. I also tried it in few other ways like init and all. It gives me error that secondary constructor not allowed without defining primary one . So how to write primary constructor.

1
Activities do not have constructors. - CommonsWare
Yeah , got the mistake :) Thank you - Pritish

1 Answers

3
votes

Two points:

  1. Use this keyword instead of super
  2. Pass a string parameter to your primary constructor

class Main2Activity(val name: String) {
    var a: Int = 0

    constructor(a: Int) : this("myString") {
        this.a = a
    }
}

Example:

val first = Main2Activity("Kotlin")
print("${first.name} ${first.a}")   // >>> Kotlin, 0

val second = Main2Activity(11)
print("${second.name} ${second.a}") // >>> myString, 11

Very nice explanation by @Oliver Charlesworth:

There are various syntactic differences [between primary and secondary constructors], clearly. But a major conceptual difference is that all secondary constructors ultimately delegate to the primary constructor.

The way I think about this is that the primary constructor is the canonical interface for creating an object, and secondary constructors are like static helpers for transforming other argument sets to comply with this interface.

For more info: Constructors