如何在Kotlin中实例化对象时覆盖方法?

时间:2017-06-17 11:17:29

标签: java android kotlin

在Java中,要在实例化新对象时覆盖方法,我们可以这样做

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

如何在Kotlin做到这一点?我尝试了这段代码,但无法编译。

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

1 个答案:

答案 0 :(得分:37)

如果要创建匿名内部类,则应使用object

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

另见Object Expressions and Declarations