有时候要求一个属性只能赋值一次,且不能为空,可以用下面的方法
本文地址: 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,或已经有了")
            }
            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
    }
}
这样所有需要实现这个需求的属性都可以用这个委托来实现。
