我有一个包含很多非空字段和可空字段的类.如果我宣布他们就好
val key : String
Run Code Online (Sandbox Code Playgroud)
在科特林编译器会当然给我一个错误,告诉我,他们需要被初始化,所以我想我应该把不能为空那些在构造函数中,并添加辅助构造,当我需要与非空值初始化为空的字段.这是为了避免调用构造函数然后调用setter,然后我会调用一个构造函数.这就是它看起来像
import utilities.Constants
import java.util.*
class Action(val key: String,
//val actionNode: ActionNode
val date: Date,
val stringValue: String,
val autoRecognitionStatus: Constants.MeasurementAutoRecognized,
val recognitionId: String,
val method: Constants.MeasurementMethod,
val userKey: String,
val userName: String,
val isInRange: Boolean) {
var pictureUrl: String? = null
var remotePictureUrl: String? = null
constructor(key: String,
// actionNode: ActionNode
date: Date,
stringValue: String,
autoRecognitionStatus: Constants.MeasurementAutoRecognized,
recognitionId: String,
method: Constants.MeasurementMethod,
userKey: String,
userName: String,
isInRange: Boolean,
pictureUrl: String?,
remotePictureUrl: String?)
: this(key,
// actionNode
date,
stringValue,
autoRecognitionStatus,
recognitionId,
method,
userKey,
userName,
isInRange) {
this.pictureUrl = pictureUrl
this.remotePictureUrl = remotePictureUrl
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是这段代码看起来很糟糕.我不是说外观最重要,但我觉得这是一个错误的方法来做到这一点.特别是当我需要委托给主构造函数时,我不得不重写大量的参数
有没有更好或"正确"的方式来做到这一点?
编辑:我在问:我是否为Kotlin可以轻松完成的事情编写了大量代码?
如果类是完整的,那么你也可以把它变成一个数据类.此外,Kotlin支持属性的默认值,因此您只需要一个构造函数,即主要构造函数.以下类看起来更好,几乎与您定义的相同.
data class Action(
val key: String,
val date: Date,
val stringValue: String,
val autoRecognitionStatus: MeasurementAutoRecognized,
val recognitionId: String,
val method: MeasurementMethod,
val userKey: String,
val userName: String,
val isInRange: Boolean,
var pictureUrl: String? = null,
var remotePictureUrl: String? = null
)
Run Code Online (Sandbox Code Playgroud)
如果需要Java的辅助构造函数,可以使用注释给定的构造函数@JvmOverloads.
| 归档时间: |
|
| 查看次数: |
130 次 |
| 最近记录: |