简体   繁体   中英

How to declare an extension static function in Kotlin on Java Classes?

I want declaring an extension func in kotlin but on Java classes Library, I know that do in Kotlin when you resolve companion in extension function. Like:

class Food {
   companion object {
       fun foo() = Unit
   }
}

fun Food.Companion.clear(){/*Clear all of objects*/}


Now, are there any way for inject a static function on Java classes library?

No you can't do it. That issue is already in tracked, please check this for more information.

Create a class somewhere in project named Extensions.kt . It should be looks like this:

package com.examplle.something

fun Food.clear(){
    /*Clear all of objects*/
}

fun User.xyz(){
    /*Do task XYZ*/
}

No need to make a class for this. It should be out of the class.

So finally we'll have a file Extensions.kt which contains only the extensions method directly without any class structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM