Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Final methods in kotlin interfaces

Tags:

kotlin

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:

  • I want the delete function to be final so that it cannot be overridden in the implementations of the interface.
  • I want the 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.

like image 962
Dimitar Spasovski Avatar asked Oct 26 '25 09:10

Dimitar Spasovski


1 Answers

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)
}
like image 193
Frank Neblung Avatar answered Oct 29 '25 09:10

Frank Neblung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!