I have defined an interface
as,
interface Manga {
fun title(): String
fun rating(): String
fun coverUrl(): String
val id: String
}
I want to change set id without affecting the mutability of the interface. So I have created an extension function that sets the id field.
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_
}
}
If I want to add field to manga interface then I have to modify the extension function.
Is there a way to override only id while creating the new object without modify the extension function? Or any other way to achieve the same effect.
Use delegation
fun Manga.setId(id_: String): Manga {
return object : Manga by this {
override val id: String
get() = id_
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.