Kotlin懒惰的默认属性

在Kotlin中,我如何定义一个具有惰性默认值的variables?

比如val就是这样的:

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

我想要做的是,有一个属性( toolbarColor )的默认值,我可以改变这个值的其他任何东西。 可能吗?

编辑:这是部分把戏。

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

有没有可能通过写作来缓解这一点

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

在默认值的计算方式懒惰? 目前它不会工作,因为color()需要一个只在稍后初始化的Context

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

 private class ColorDelegate(initializer: () -> T) : ReadWriteProperty { 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  lazyColor(initializer: () -> T): ReadWriteProperty = 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开始)。 我会看看是否可以用较少的代码完成。

你可以将你的财产存储在地图上 ,基本上创建一个可变的懒惰。 你需要一个具有默认function的可变映射(如HashMap )来委托给:

 var toolbarColor by hashMapOf() .withDefault { toolbarColor = R.color.colorPrimary; toolbarColor } 

您还需要导入一些扩展函数: import kotlin.properties.getValueimport kotlin.properties.setValue

如果Kotlin提供了一些内置和优化的东西(比如mutableLazy或者其他东西),那将会很好。 因此,我创建了KT-10451 。