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() } }
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With