Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

generics - Query related with kotlin class

class student1(firstName : String, lastName : String){
    var id : Int = -1
    val firstName = firstName
    val lastName = lastName

    init {
       println("initialized")
    }

    constructor(firstName : String, lastName : String, extraParam : Int) : this(firstName, lastName){    
        this.id = extraParam
    }
    
    fun callme(){
        print(firstName + lastName)
    }
}


class student2(firstName : String, lastName : String){
    val firstName = firstName
    val lastName = lastName
    
    fun callme() {
        print(firstName + lastName)
    }
}

fun main() {

  val p1 = student1("shubham", "sharma")   
  println(p1.firstName)
  println(p1.lastName)
  println(p1.callme())
  val p2 = student1("shubham", "sharma")   
  println(p2.firstName)
  println(p2.lastName)
  println(p2.callme())

}

here in both the class, the output is the same with the same parameter then why we need to use the secondary constructor? What is the main difference between these two class please let me know with one example. will be appreciated!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

the first one has two constructors that get an additional variable but does not use it, that's why you don't see the difference. the student1 class has an optional id which is -1 by default. if you don't use it somewhere else you must remove it. actually, we don't create classes like this in kotlin you can move the var, val keywords in the constructor:

class Student1(val firstName : String, val lastName : String) {

    var id = -1
    
    init {
        println("initialized")
    }

    constructor(firstName : String, lastName : String, id: Int = -1) : this(firstName, lastName) {
        this.id = id
    }

    fun callme() {
        print(firstName + lastName)
    }
}

you can even make this shorter with default arguments and remove the secondary constructor and make id a val (if you don't want to change it):

class Student1(val firstName : String, val lastName : String, val id: Int = -1) {
    
    init { println("initialized") }

    fun callme() { print(firstName + lastName) }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...