2017-06-17 61 views
7

在Java中,以實例化新的對象,我們可以做到這一點如何在Kotlin中實例化對象時重寫方法?

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

如何做,在科特林時覆蓋的方法?我試過這段代碼,但沒能編譯。

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

你得到的錯誤是什麼? –

+0

@NihalSaxena它不會編譯,IDE說類型不匹配和未解決的參考。 – aldok

回答

13

如果你想創建匿名內部類,你應該使用object

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

另請參閱Object Expressions and Declarations