Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement optional functions in an abstract class

Tags:

kotlin

In Kotlin I have an abstract class that other classes can inherit from. I would like to have some functions that the class that inherits this class can optionally implement. In the code below, the function is protected abstract. This however requires that the class that is inheriting this class MUST implement these functions. Is there a way to make it so that the class that is inheriting can choose to implement the functions or not implement them?

abstract class BaseDialogFragment {
    protected abstract fun getButton1Text(): String
    protected abstract fun getButton2Text(): String
}
like image 820
Johann Avatar asked Jun 08 '26 15:06

Johann


1 Answers

It is very simple, you just provide the default implementation like in the example below and your inheritors can override them:

abstract class BaseDialogFragment {

    open fun getButton1Text(): String {
        TODO("Your default implementation here")
    }

    open fun getButton2Text(): String {
        TODO("Your default implementation here")
    }
}
like image 117
Adam Arold Avatar answered Jun 10 '26 06:06

Adam Arold