How to override method when instantiating object i

2019-03-24 05:22发布

问题:

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()
    }
} 

回答1:

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.