Snehil
Snehil

Reputation: 45

Kotlin extension function and interface

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() = [email protected]()

        override fun rating() = [email protected]()

        override fun coverUrl() = [email protected]()

        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.

Upvotes: 1

Views: 1519

Answers (1)

IR42
IR42

Reputation: 9672

Use delegation

fun Manga.setId(id_: String): Manga {
    return object : Manga by this {
        override val id: String
            get() = id_
    }
}

Upvotes: 6

Related Questions