Hacen Selahy
Hacen Selahy

Reputation: 79

Accidental override kotlin

I have this class

open class BaseActivity : AppCompatActivity() {

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_base)
  }
}

being superclass of this

class MainActivity : BaseActivity() {

  protected fun onCreate(savedInstanceState: Bundle) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
  }
}

and got an error: accidental override the declarations: protected open onCreate() protected final onCreate()

Upvotes: 1

Views: 771

Answers (1)

zsmb13
zsmb13

Reputation: 89578

You have to explicitly mark functions with the override keyword to override them (as described in the documentation here):

class MainActivity : BaseActivity() {

  override fun onCreate(savedInstanceState: Bundle) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
  }

}

If you leave out this keyword, the compiler will think that you've accidentally named a function the same as another function in the base class, hence the warning about an "accidental override".

You can also drop the protected keyword as this method will already have that visibility from the declaration in the AppCompatActivity base class.

Upvotes: 3

Related Questions