Reputation: 2132
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:
delete
function to be final
so that it cannot be
overridden in the implementations of the interface.validateCanDelete
and deleteNewsItem
methods to be overridden in
the implementations of the interface.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
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