假设我有以下类:
data class StuffWithParams<T>(
val value: T,
val params: MutableMap<String, Any> = mutableMapOf()
)
然后你可以像这样delegate additional properties to the map:
data class StuffWithParams<T>(/* */) {
val name by params;
}
现在,我想向该类的typed instances个添加扩展属性,如下所示:
val StuffWithParams<Car>.speed: Int by params
这将导致错误显示为Unresolved reference: params
.
val StuffWithParams<Car>.speed: Int by this.params
这反过来会导致错误显示为'this' is not defined in this context
.
通过将其转换为一个getter属性,您可以以某种方式"绕过"此限制:
val StuffWithParams<Car>.speed: Long get() { val speed: Long by params; return speed }
...但它很难看,而且增加了所需的样板数量.
这是故意的吗?在扩展属性委托的情况下,这是不是解决this
的方式中的一个错误?
有没有更优雅的方式来实现这一点?