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?

1
  • 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) Commented Nov 23, 2019 at 9:30

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

-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.

3 Comments

I want to inject a static fun in Java Classes library like Navigation Component that developed by Java
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.
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().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.