Simulan88
Simulan88

Reputation: 185

Kotlin force override of a function

I'm creating a base class.
I have start() with some code.
And a bar() that needs to be overidden by a class that inherits Foo

start() calls bar()

My example (foo.kt) :

open class Foo {
    fun start() {
        bar()
        //...
    }
    fun bar() {
        TODO("implement me in deriving class")
    }
}

I don't like bar() throwing an exception I don't like leaving bar() with blank body either

Is there something I forgot that is a better alternative in Kotlin?

Upvotes: 6

Views: 5163

Answers (1)

zsmb13
zsmb13

Reputation: 89548

You can make your method (and consequently, your class) abstract:

abstract class Foo {
    fun start() {
        bar()
        //...
    }
    abstract bar()
}

This will force any non-abstract class that inherits from Foo to implement the bar method, as well as prevent anyone from creating an instance of the base Foo class directly.

Upvotes: 12

Related Questions