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

285 Views Asked by At

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?

2

There are 2 best solutions below

0
Rujul Gandhi On BEST ANSWER

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

3
Abdur Rahman On

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.