Kotlin惰性默认属性 [英] Kotlin lazy default property

查看:99
本文介绍了Kotlin惰性默认属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Kotlin中,如何定义具有默认默认值的var?

In Kotlin, how do i define a var that has a lazy default value ?

例如,val可能是这样的:

val toolbarColor  by lazy {color(R.color.colorPrimary)}

我想做的是,为某些属性(toolbarColor)设置一个默认值,然后我可以为其他任何属性更改该值.是否有可能?

What i want to do is, have a default value for some property (toolbarColor), and i can change that value for anything else. Is it possible?

这可以做部分技巧.

var toolbarColor = R.color.colorPrimary
    get() = color(field)
    set(value){
        field = value
    }

是否可以通过编写

var toolbarColor = color(R.color.colorPrimary)
    set(value){
        field = value
    }

以某种方式延迟计算默认值?目前,它不起作用,因为color()需要一个仅在以后初始化的Context.

in a way that the default value is computed lazily? At the moment it won't work because color() needs a Context that is only initialized later.

推荐答案

您可以创建自己的委托方法:

You can create your own delegate method:

private class ColorDelegate<T>(initializer: () -> T) : ReadWriteProperty<Any?, T> {

    private var initializer: (() -> T)? = initializer

    private var value: T? = null

    override fun getValue(thisRef: Any?, property: KProperty<*>): T {
        return value ?: initializer!!()
    }

    override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        this.value = value
    }
}

在某些委托中声明:

object DelegatesExt {
    fun <T> lazyColor(initializer: () -> T): ReadWriteProperty<Any?, T> = ColorDelegate(initializer)
}

并按如下方式使用:

var toolbarColor by DelegatesExt.lazyColor {
    // you can have access to your current context here.
    // return the default color to be used
    resources.getColor(R.color.your_color)
}

...

override fun onCreate(savedInstanceState: Bundle?) {
    // some fun code
    // toolbarColor at this point will be R.color.your_color
    // but you can set it a new value
    toolbarColor = resources.getColor(R.color.new_color)
    // now toolbarColor has the new value that you provide.
}

我认为这可能是一种更清洁的方法,但是我还不知道(从几天前的kotlin开始).我将看一下是否可以用更少的代码来完成.

I think this could be a cleaner way to do, but I don't know yet (starting with kotlin few days ago). I will take a look and see if this could be done with less code.

这篇关于Kotlin惰性默认属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆