80,351
社区成员
发帖
与我相关
我的任务
分享
class Table {
private String mDate;
private String mTime;
private double mPrice;
private double mPriceBBBBBB;
Table(String date, String time, double price) {
mDate = date;
mTime = time;
mPrice = price;
}
Table(String date, double priceBBBBBB) {
mDate = date;
mPriceBBBBBB = priceBBBBBB;
}
}
data class Table(var date: String) {
private var time: String? = null
private var price = 0.0
private var priceBBBBBB = 0.0
constructor(date: String, time: String?, price: Double):this(date) {
this.time = time
this.price = price
}
constructor(date: String, priceBBBBBB: Double) :this(date){
this.priceBBBBBB = priceBBBBBB
}
}
data class Student(val no: Int, val name: String, val weight: Int) {
var height = 0
constructor(no: Int, height: Int) : this(no, "", 0) {
this.height = height
}
// 其它重写
}
fun test() {
Student(21, "Zhang San", 65)
Student(21, 158)
}
data class Student(val no: Int, val name: String, val weight: Int)
应该很容易理解。
从构造器我们需要的是一个包含了no和height的值,并且从构造器我们需要去给主构造器赋值,因此我们可以把从构造器写成这样
constructor(no: Int, height: Int) : this(no, "", 0)
再然后我们在使用主构造器赋值之后仍然可能有赋值height的需求,并且我们从构造器中传入的height值也需要一个存放的位置,因此我们需要在方法内部放一个变量
var height = 0
再往你的从构造器里添加对应的赋值方法
this.height = height
最后,因为我们新添加的属性不会直接被data识别,因此我们需要单独重写tostring、hashcode等方法
override fun toString(): String {
return "Student(no=$no, name='$name', weight=$weight, height=$height)"
}
//下略
可以看到写到最后已经和直接用java写差不多繁琐了,因此不是特殊需求不要这样写,另外遇到问题多思考一下,这些东西按我之前说的内容完全可以推理出来的val wt = Student(21, "Zhang San", 65)
val ht = Student(21,170)
data class Student(val no: Int, val name: String,val height: Int, val weight: Int) {
constructor(no: Int) : this(no, "", 0, 0)
}
data class Student(val no: Int, val name: String = "", val height: Int = 0, val weight: Int = 0) {
}
这样初始化:
val wt = Student(21, "Zhang San", 0, 65)
val ht = Student(21,"",170)
问题有两个:
第一,已经给name、height、weight默认值了,但初始化的时候还需要再输入一次。
第二,wt的height必须是默认值0,但上面的初始化无法保证,例如wt = Student(21, "Zhang San", -999, 65)。ht同理。
需求的两种初始化方式如下面所示,而且必须只有这两种方式。但似乎无法实现:
val wt = Student(21, "Zhang San", 65)
val ht = Student(21,170)
比如,我建立下面所示的类,会有3个构造器,多出1个构造器。
data class Student(val no: Int) {
var name = ""
var height = 0
var weight = 0
constructor(no: Int, name: String, weight: Int) : this(no) {
this.name = name
this.weight = weight
}
constructor(no: Int, height: Int) : this(no) {
this.height = height
}
}