Hello imagine that we have following class
Manager{
public static void doSth(){
// some logic
};
}
How to override that method in kotlin?
I've tired to use
fun Manager.doSth(){}
but Its applied to instance not a static type.
Purpose of doing that is to avoid using PowerMockito
Short Answer
No
"Short" Explanation
You can only override virtual methods and also you can shadow/replace static methods in Java, but you can't shadow a "static" method in Kotlin as the static method will not be available using the child class qualifier already. And even when using extension methods, you simply can't do it for either static or non-static as the member function will always win(see the example below). What you can do is to subclass the parent and add a new companion object that has a method with the same name as the parent and call the parent method from inside.
Full Explanation
companion object
which behaves similarly and you can access the method of the companion object as if it were a java static method using only the class name as a qualifier but you can't access the methods of companion object of a parent class from its child like Java.Example
You can't do that in Kotlin. The problem is that there is no
static
keyword in Kotlin. There is a similar concept (companion object
) but the problem is that your original Java class doesn't have one.static
methods don't support inheritance either so you can't help this on the Java side.If you want to declare extension methods which are "static" (eg: put them on a
companion object
) you can do this:Then you can call it like this:
Note that you can only augment Kotlin classes this way which have a
companion object
.