Search code examples
classinheritancekotlincompilationfinal

Why kotlin script file cannot have inherited class in the same file?


I'm wring my.kts script, and use it to run kotlin, I've got this:

class TestA {
    init {}
    open fun testOpen() {
        println(this)
    }
}
class TestB : TestA {
    override fun testOpen() {
        super.testOpen()
    }
}

It fails to compile, saying that:

error: this type is final, so it cannot be inherited from
class TestB : TestA {
          ^
basic.kts:39:15: error: this type has a constructor, and thus must be     initialized here

class TestB : TestA {


Solution

  • If you inherit one class from another and base class has primary constructor, it must be initialised. Your TestA has default primary constructor, so it should look like:

    class TestB : TestA() {
        override fun testOpen() {
            super.testOpen()
        }
    }
    

    Another problem is that classes in kotlin are final by default and you should explicitly define that they can be extended:

    open class TestA
    

    Check this examples for more information.