2

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?

ImanX
  • 789
  • 6
  • 23
  • As far as I understand it's not possible as long as a class have no companion object. Btw there is no "injection" of functions. The compiler transforms your `fun A.ext(): B` into a `static B ext(A receiver)` – gpunto Nov 23 '19 at 09:30

2 Answers2

5

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

Rujul Gandhi
  • 1,700
  • 13
  • 28
-2

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.

Abdur Rahman
  • 894
  • 1
  • 11
  • 27
  • I want to inject a static fun in Java Classes library like `Navigation Component` that developed by Java – ImanX Nov 23 '19 at 09:23
  • This will work fine with any class. Just replace the Food or User to specific class name that you want to insert a new method in. – Abdur Rahman Nov 23 '19 at 10:18
  • You call it on objects. OP wants to call it on class. Imagine `fun Int.increment() = this + 1` being called like `1.increment()` not `Int.increment()`. – Eugen Pechanec Nov 23 '19 at 10:25