如何在一个类函数中使用来自多个构造函数的变量?-科特林



我正在用不同的构造函数创建一个简单的数据类。我想让一个函数对两种实例类型都可以访问,而不需要写两次。如何做到这一点?

例如:

class myClass private constructor() {
constructor(
weather: String, 
day: Int?
) : this() {
//I can put assignment here
}
constructor(
day: Int?
) : this() {
//and here, but can this be done more efficiently?
}
val dayString: String = when(day) { //kotlin doesn't recognize 'day' variable here outside of constructors...
0 -> "Sunday"
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6 -> "Saturday"
else -> "Not a valid day of the week!"
}
}

所以当前day: Int?只是一个构造函数参数,而不是实例属性。您应该在主构造函数中将其声明为val day: Int?,以便dayString工作。当然,这只适用于主要(主(构造函数,您的类将如下所示:

class myClass private constructor(val day: Int?) {
constructor(
weather: String,
day: Int?
) : this(day) {
//I can put assignment here
}
val dayString: String = when(day) { //kotlin doesn't recognize 'day' variable here outside of constructors...
0 -> "Sunday"
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6 -> "Saturday"
else -> "Not a valid day of the week!"
}
}

如果你不喜欢这样:-为构造函数参数添加默认值,如val day: Int? = null-或添加要保存的互联网属性(如var _day: Int? = null(

最新更新