Aldo Wachyudi
Aldo Wachyudi

Reputation: 17991

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

Upvotes: 41

Views: 24801

Answers (1)

uramonk
uramonk

Reputation: 1232

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.

Upvotes: 67

Related Questions