简体   繁体   中英

How to override method when instantiating object in Kotlin?

In Java, to override method when instantiating new object we can do this

public ActivityTestRule<MainActivity> rule = new ActivityTestRule<MainActivity>(
            MainActivity.class) {
        @Override
        protected void beforeActivityLaunched() {
            // implement code
            super.beforeActivityLaunched();
        }
    };

How to do that in Kotlin? I tried this code but it failed to compile.

@Rule @JvmField
var rule = ActivityTestRule<MainActivity>(MainActivity::class.java) {
    override fun beforeActivityLaunched() {
        super.beforeActivityLaunched()
    }
} 

If you want to create anonymous inner class, you should use object .

var rule = object : ActivityTestRule<MainActivity>(MainActivity::class.java) {
    override fun beforeActivityLaunched() {
        super.beforeActivityLaunched()
    }
}

See also Object Expressions and Declarations .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM