69

I have created a Kotlin Activity, but I am not able to extend the activity. I am getting this message: This type is final, so it cannot be inherited from. How to remove final from Kotlin's activity, so it can be extended?

iknow
  • 8,358
  • 12
  • 41
  • 68
Logo
  • 1,366
  • 2
  • 11
  • 16
  • If ones final, you shouldn't try to extend it. That would defeat the purpose of it being `final`. What class are you trying to extend? – Carcigenicate Jul 18 '17 at 13:54

4 Answers4

89

As per Kotlin documentation, open annotation on a class is the opposite of Java's final. It allows others to inherit from this class. By default, all classes in Kotlin are final.

open class Base {
    open fun v() {}
    fun nv() {}
}

class Derived() : Base() {
    override fun v() {}
}

Refer :https://kotlinlang.org/docs/reference/classes.html

xarlymg89
  • 2,552
  • 2
  • 27
  • 41
Girish Arora
  • 966
  • 6
  • 7
  • 1
    What is the reason for making the classes final by default in Kotlin? – Dhruvam Sharma Oct 15 '19 at 08:31
  • 5
    @DhruvamSharma the only reason to do it was to annoy the programmers. Absolutely no other sound reason. There is a lot of discussion in Internet and most people believe it was a silly decision. – Eugene Kartoyev Apr 10 '20 at 22:16
  • 1
    Haha , Thank you – Dhruvam Sharma Apr 11 '20 at 05:59
  • Thanks a lot. I was able to infer the answer. Wish you had given slightly more description to speed up understanding whats going on. I simply had to make my function open for the error to go away. I don't understand the discussion about classes being final or not. – nyxee Apr 24 '20 at 10:29
  • @DhruvamSharma I don't know but I would guess for performance reasons. Virtual or open functions have a lot more performance overhead because it has to be looked up in a table – milkwood1 Mar 09 '21 at 10:37
27

By default the Kotlin activity is final, so we cannot extend the class. To overcome that we have to make the activity open so that, it can be extendable.

as like open class BaseCompatActivity : AppCompatActivity() { }

xarlymg89
  • 2,552
  • 2
  • 27
  • 41
Logo
  • 1,366
  • 2
  • 11
  • 16
25

In Kotlin, the classes are final by default that's why classes are not extendable.

The open annotation on a class is the opposite of Java's final: it allows others to inherit from this class. By default, all classes in Kotlin are final. Kotlin - Inheritance

open class Base(p: Int)

class Derived(p: Int) : Base(p)
Waqar UlHaq
  • 6,144
  • 2
  • 34
  • 42
1
class Base

Simple add open for super/parrent class:

open class Base
Fortran
  • 2,218
  • 2
  • 27
  • 33