繁体   English   中英

您可以在不可为空的属性上使用客户吸气剂吗?

[英]Can you have customer getter on a non-nullable property?

有没有更简单的方法来执行以下操作?

    val placeholder: Bitmap
        get() { if (_placeholder == null)
            _placeholder = BitmapFactory.decodeResource(appContext.resources, fancy_placeholder)
        /** do something else here **/
        return  _placeholder!! }
    private var _placeholder: Bitmap? = null

为此目的有一个惰性委托:

val placeholder: Bitmap by lazy { 
    BitmapFactory.decodeResource(appContext.resources, fancy_placeholder) 
}

如果您不担心线程安全,那么它的重量更轻,但更简洁:

val placeholder: Bitmap by lazy(LazyThreadSafetyMode.NONE) { 
    BitmapFactory.decodeResource(appContext.resources, fancy_placeholder) 
}

以下可能是一个解决方案:

fun <G: Any> lazyGetter(init: ()->G, onGet: G.()->Unit): ReadOnlyProperty<Any?, G> =
    object : ReadOnlyProperty<Any?, G> {
        private var value: G? = null
        override fun getValue(thisRef: Any?, property: KProperty<*>): G {
            if (value == null) value = init(); value!!.onGet(); return value!! } }

这使得上面的例子像这样:

    val placeholder: Bitmap by lazyGetter({
        BitmapFactory.decodeResource(appContext.resources, fancy_placeholder) }) {
        /** do something else here **/ }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM