Is it possible to override static method in Kotlin?

后端 未结 2 2006
难免孤独
难免孤独 2021-01-24 03:17

Hello imagine that we have following class

Manager{
   public static void doSth(){
      // some logic
   };
}

How to override that method in k

2条回答
  •  [愿得一人]
    2021-01-24 03:40

    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

    • Static methods can't be overridden. It's called shadowing as you hide a method with another one.
    • There are no static methods in Kotlin, so what you can do is using the 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.
    • You can't shadow a static method in Kotlin as the static method will not be available using the child class qualifier already, but you can write another companion object and add a method with the same name and call the parent method from there as the method from parent can't be accessed with the child class name qualifier.
    • You can't make an extension method that shadows a companion object method or even overrides a member method. If a class has a member function and an extension function is defined which has the same receiver type, the same name and is applicable to given arguments, the member always wins.
    • Companion object extension: You can write an extension method to the companion object, but if a member of that companion object has the same signature the member will always win.

    Example

    open class A {
        fun foo() {
            println("A.foo()")
        }
        companion object {
            fun bar() {
                println("A.Companion.bar()")
            }
        }
    }
    
    class B: A()
    
    fun A.foo() {
       println("A.foo() extension")
    }
    
    fun A.Companion.bar() {
        println("A.Companion.bar() extension")
    }
    
    fun A.Companion.baz() {
        println("A.Companion.baz() extension")
    }
    
    fun main(args: Array) {
        A().foo() // prints A.foo()
        A.bar() // prints A.Companion.bar()
        A.baz() // prints A.Companion.baz() extension
        B.bar() // COMPILE ERROR
    }
    

提交回复
热议问题