Kotlin: How can I create a “static” inheritable function?

后端 未结 3 1059
野的像风
野的像风 2020-12-06 04:43

For example, I want to have a function example() on a type Child that extends Parent so that I can use the function on both.



        
3条回答
  •  醉梦人生
    2020-12-06 05:17

    Since companion objects play by the same rules as any others, it is easy to use normal means of code reuse on them:

    open class Example {
        fun example() {}
    }
    
    class Parent {
        companion object : Example()
    }
    
    class Child {
        companion object : Example()
    }
    
    fun main(args: Array) {
        Child.example()
        Parent.example()
    }
    

    Alternatively with class delegation you can reuse the implementation from Parent directly:

    interface Example {
        fun example()
    }
    
    class Parent {
        companion object : Example {
            override fun example() {}
        }
    }
    
    class Child {
        companion object : Example by Parent.Companion
    }
    

提交回复
热议问题