Is it possible to override static method in Kotlin?

后端 未结 2 2008
难免孤独
难免孤独 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:44

    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:

    class Manager {
    
        companion object
    }
    
    fun Manager.Companion.doSth() = println("sth")
    

    Then you can call it like this:

    Manager.doSth()
    

    Note that you can only augment Kotlin classes this way which have a companion object.

提交回复
热议问题