Dimitar Spasovski
Dimitar Spasovski

Reputation: 2132

Final methods in kotlin interfaces

As the title states, I am looking for a way to implement a final (method that cannot be overridden) in a kotlin interface. So here is my code:

interface NewsItemState {

    final fun delete(newsItem: NewsItem) {
        validateCanDelete(newsItem)
        deleteNewsItem(newsItem)
    }

    fun validateCanDelete(newsItem: NewsItem)
    fun deleteNewsItem(newsItem: NewsItem)
}

And here is my use case:

Now, I know that this is not possible at the moment and that adding final to a method is not allowed in the interface. I also know that I can achieve this by replacing the interface with an abstract class.

However, I was wondering if there is a way of implementing the same functionality in an interface because my final method is not going to have any "state managing" logic.

Upvotes: 4

Views: 4259

Answers (1)

Frank Neblung
Frank Neblung

Reputation: 3175

While it's not possible to have final methods in interfaces, it's absolute OK to define extension methods for interface types.

interface NewsItemState {
    fun validateCanDelete(newsItem: NewsItem)
    fun deleteNewsItem(newsItem: NewsItem)
}

fun NewsItemState.delete(newsItem: NewsItem) {
    validateCanDelete(newsItem)
    deleteNewsItem(newsItem)
}

Upvotes: 9

Related Questions