Cheok Yan Cheng
Cheok Yan Cheng

Reputation: 42710

Is there an easy way to call parent super function from inner class?

I have the following code

class DrawingActivity : AppCompatActivity() {


    private inner class ImageInfoObserver : Observer<ImageInfo> {
        override fun onChanged(imageInfo: ImageInfo?) {
            // Is there a way to perform DrawingActivity.super.finish() ?
            superFinish()
        }
    }

    fun superFinish() {
        super.finish()
    }
    
    override fun finish() {
        ...
        super.finish()
    }

Currently, I need to specially create superFinish() function, in order for inner class ImageInfoObserver to call DrawingActivity.super.finish()

I was wondering, is there an easier way to accomplish so, without having to create superFinish()?

Upvotes: 1

Views: 484

Answers (1)

cactustictacs
cactustictacs

Reputation: 19544

You do it in the same way you access DrawingActivity - but instead of this@DrawingActivity you use super@DrawingActivity instead. So

[email protected]()

would be like calling super.finish() from inside DrawingActivity. The docs have an example too.

Is there any reason you don't want to call finish() on the actual class though? (i.e. [email protected]()) Why do you want to skip the DrawingActivity's own finish code? If there's a good reason for it, it might be worth making the extra code in the overridden finish() function conditional on some state variable.

That way it's clear from reading the function when certain stuff happens and when it doesn't, and all the finish teardown logic is handled in one place.

Upvotes: 2

Related Questions