我有以下课程。
class Student(id: String, name: String) {
var id: String? = null
var name: String? = null
var grade: String? = null
constructor(id: String, name: String, grade: String) : this(id,name) {
this.grade = grade
}
}
使用:
var student = Student("AB001","Smith","N/A")
prinln(student.id + student.name + student.grade)
输出:
nullnullN / A
任何人都可以解释为什么我从默认构造函数中获取输出null吗?
答案 0 :(得分:5)
class Student {
var id: String? = null
var name: String? = null
var grade: String? = null
constructor(id: String, name: String) {
this.id=id
this.name=name
}
constructor(id: String, name: String, grade: String) : this(id, name) {
this.grade = grade
}
}
或
class Student(var id: String?, var name: String?) {
var grade: String? = null
constructor(id: String, name: String, grade: String) : this(id, name) {
this.grade = grade
}
}
答案 1 :(得分:4)
除了其他答案,还有另一种方法。使用主构造函数参数直接初始化属性:
class Student(id: String, name: String) {
var id: String? = id
var name: String? = name
var grade: String? = null
constructor(id: String, name: String, grade: String) : this(id,name) {
this.grade = grade
}
}
注意,由于id
和name
始终使用不可为空的值进行初始化,因此您可以省略?
。除此之外,您可以使用主构造函数中的默认值省略辅助构造函数:
class Student(id: String, name: String, grade: String? = null) {
var id: String = id
var name: String = name
var grade: String? = grade
}
但是现在我们只剩下一个构造函数,所以我们可以将属性直接拉到构造函数中:
class Student(
var id: String,
var name: String,
var grade: String? = null
)
因为类的主体现在是空的,所以我也省略了花括号。
答案 2 :(得分:1)
或者
class Student(id: String, name: String) {
var id: String? = null
var name: String? = null
var grade: String? = null
init {
this.id = id
this.name = name
}
constructor(id: String, name: String, grade: String) : this(id,name) {
this.grade = grade
}
}
init块是你在主构造函数中使用参数的方式,当它们没有被标记为val或vars时必须完成。
换句话说,由于您没有将主构造函数中的参数(类名旁边的括号)标记为val或vars,因此它们不会自动指定为属性。为了在主构造函数中使用参数,特别是那些没有被标记为vars和val的参数,你需要一个init块。
我不禁想到你真正想要的是这个但是:
class Student (var id: String, var name: String, var grade: String? = null)
甚至可能将它们改为val而不是vars。