Static extension methods in Kotlin

后端 未结 8 2374
生来不讨喜
生来不讨喜 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:19

    Since I keep coming across this when searching, here's a different approach I haven't seen anyone mention that works in a static way and it works with generics!

    Extension definitions:

    // Extension function
    fun  KClass.doSomething() = /* do something */
    
    // Extension Property
    val  KClass.someVal get() = /* something */
    

    Usage:

    MyType::class.doSomething()
    
    MyType::class.someVal
    

    As you can see, the trick is attaching the extension function to the KClass of the type instead since that can be referenced statically.

提交回复
热议问题