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

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

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

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

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

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

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

另请参见对象expression式和声明 。