Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()     } }  
like image 532
aldok Avatar asked Jun 17 '17 11:06

aldok


People also ask

How do you override a method in Kotlin?

To override a method of the base class in the derived class, we use the override keyword followed by the fun keyword and the method name to be overridden.

How do you override property in Kotlin?

Overriding Properties To allow child classes to override a property of a parent class, you must annotate it with the open modifier. You can override a super class property either using an initializer or using a custom getter/setter.

What does override mean in Kotlin?

In Kotlin, implementation inheritance is regulated by the following rule: if a class inherits multiple implementations of the same member from its immediate superclasses, it must override this member and provide its own implementation (perhaps, using one of the inherited ones).


1 Answers

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.

like image 112
uramonk Avatar answered Sep 28 '22 08:09

uramonk