有時候要求一個屬性只能賦值一次勤婚,且不能為空,可以用下面的方法
本文地址: http://blog.csdn.net/qq_25806863/article/details/73277876
用get和set
利用屬性的get()和set()對值進行控制:
class APP : Application() {
companion object {
var app: Application? = null
set(value) {
field = if (field == null&& value!=null) value else throw IllegalStateException("不能設置為null飒货,或已經(jīng)有了")
}
get() {
return field ?: throw IllegalStateException("還沒有被賦值")
}
}
override fun onCreate() {
super.onCreate()
app = this
}
}
用委托實現(xiàn)
自定義一個委托屬性:
class NotNUllSingleVar<T> : ReadWriteProperty<Any?, T> {
private var value: T? = null
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return value ?: throw IllegalStateException("還沒有被賦值")
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
this.value = if (this.value == null&&value!=null) value else throw IllegalStateException("不能設置為null醋奠,或已經(jīng)有了")
}
}
然后對屬性使用就行了:
class APP : Application() {
companion object {
var app: Application? by NotNUllSingleVar()
}
override fun onCreate() {
super.onCreate()
app = this
}
}
這樣所有需要實現(xiàn)這個需求的屬性都可以用這個委托來實現(xiàn)。