1. 程式人生 > >Kotlin讓屬性只能被賦值一次且不能為空

Kotlin讓屬性只能被賦值一次且不能為空

有時候要求一個屬性只能賦值一次,且不能為空,可以用下面的方法

用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,或已經有了"
) } get() { return field ?: throw IllegalStateException("還沒有被賦值") } } override fun onCreate() { super.onCreate() app = this } }

用委託實現

自定義一個委託屬性:

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,或已經有了") } }

然後對屬性使用就行了:

class APP : Application() {
    companion object {
        var app: Application? by NotNUllSingleVar()
    }
    override fun onCreate() {
        super.onCreate()
        app = this
    }
}

這樣所有需要實現這個需求的屬性都可以用這個委託來實現。