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) }
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…