我已将interface
定义为
interface Manga {
fun title(): String
fun rating(): String
fun coverUrl(): String
val id: String
}
我想更改集合ID,而又不影响接口的可变性。因此,我创建了一个扩展函数来设置id字段。
fun Manga.setId(id_: String): Manga {
return object : Manga {
override fun title() = this@setId.title()
override fun rating() = this@setId.rating()
override fun coverUrl() = this@setId.coverUrl()
override val id: String
get() = id_
}
}
如果要向漫画界面添加字段,则必须修改扩展功能。
是否有一种方法可以在创建新对象时仅覆盖id而无需修改扩展功能?或通过其他任何方式达到相同的效果。
答案 0 :(得分:6)
fun Manga.setId(id_: String): Manga {
return object : Manga by this {
override val id: String
get() = id_
}
}