Can not inherit from final class

Gabriel Kuka :

I have just created my first android library. At another application I want to extend a class from the it. But it shows me an error: "Cannot extend from final 'library.com.kukaintro.activities.KukaIntro'".enter image description here

enter image description here

As you can see none of the super classes are final. If I click at the super class KukaIntro (at the app not at the library) it says this: enter image description here

This is my first time creatin a library. Can someone show me how can I manage to fix this problem?

Bob :

In Kotlin, unlike Java, all the classes are implicitly marked final by default. If you want to inherit from a class, you have to explicitly add open keyword before the class declaration.

open class Base(p: Int) {

}

If you want to override any functions from the super class, again you have to add the open keyword to those functions in the super class, and the override keyword is mandatory for the overridden function in the sub class.

Example from the doc:

open class Foo {
    open fun f() { println("Foo.f()") }
    open val x: Int get() = 1
}

class Bar : Foo() {
    override fun f() { 
        super.f()
        println("Bar.f()") 
    }

    override val x: Int get() = super.x + 1
}

Kotlin docs: https://kotlinlang.org/docs/reference/classes.html#inheritance

Here is the discussion about this language design: https://discuss.kotlinlang.org/t/classes-final-by-default/166

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=470060&siteId=1