Static extension methods in Kotlin

后端 未结 8 2366
生来不讨喜
生来不讨喜 2020-12-05 03:55

How do you define a static extension method in Kotlin? Is this even possible? I currently have an extension method as shown below.

public fun Uber.doMagic(co         


        
8条回答
  •  温柔的废话
    2020-12-05 04:08

    This is what the official documentation says:

    Kotlin generates static methods for package-level functions. Kotlin can also generate static methods for functions defined in named objects or companion objects if you annotate those functions as @JvmStatic. For example:

    Kotlin static methods

    class C {
      companion object {
        @JvmStatic fun foo() {}
        fun bar() {}
      }
    }
    

    Now, foo() is static in Java, while bar() is not:

    C.foo(); // works fine
    C.bar(); // error: not a static method
    

提交回复
热议问题