Reputation: 344
I'm trying to replace Dagger 2 to Koin in my current project and I don't want to rewrite some classes in Kotlin to use it.
Is possible to inject with Koin in java classes?
In Kotlin is just
// Inject MyPresenter
val presenter : MyPresenter by inject()
Thanks
Upvotes: 18
Views: 15578
Reputation: 2785
Use
// Java Compatibility
implementation "io.insert-koin:koin-android-compat:$koin_version"
Instead
implementation "org.koin:koin-java:$koin_version"
Don't forget
// Add Maven Central to your repositories if needed
repositories {
mavenCentral()
}
Importante point
Due to Jcenter shutdown, the koin project's maven group id was previously org.koin and is now io.insert-koin. Please check your configuration with modules below.
See official documentation here
Have a good job!
Upvotes: 2
Reputation: 936
Yes it is Possible. Just sync project with this gradle file
implementation "org.koin:koin-java:$koin_version"
In your java class replace
// Inject MyPresenter
private val presenter : MyPresenter by inject()
with
private Lazy<MyPresenter> presenter = inject(MyPresenter.class);
and get presenter method inside Java class like
presenter.getValue().sayHello()
Upvotes: 28
Reputation: 444
You no longer need the additional koin-java
dependency as this is now a part of koin-android
& koin-core
.
// Imports
import static org.koin.java.KoinJavaComponent.get;
import static org.koin.java.KoinJavaComponent.inject;
import static org.koin.core.qualifier.QualifierKt.named;
import static org.koin.core.parameter.DefinitionParametersKt.parametersOf;
// Lazy injection
Lazy<MyDependency> dependency = inject(MyDependency.class);
// Eager injection
MyDependency dependency = get(MyDependency.class);
// Named injection
get(MyDependency.class, named("MyNamedDependency"));
// Parameter injection
get(MyDependency.class, null, () -> parametersOf(this));
Upvotes: 13
Reputation: 1809
following code worked for me without org.koin:koin-java:$koin_version dependency:
private MyPresenter presenter = org.koin.java.KoinJavaComponentKoinJavaComponent.inject(MyPresenter.class).getValue();
Upvotes: 0
Reputation: 1686
It is, make sure you import in gradle the koin for java library and use above answers.
Gradle:
implementation "org.koin:koin-java:2.0.1"
Upvotes: 0
Reputation: 763
A class or file can either have .kt extension means Kotlin, or have .java extension means Java. You can't write a file or class in both the languages simultaneously.
But your Java and Kotlin files can talk with each other, i.e you can a Java class with a variable and access that variable in your Kotlin file or vice-versa.
So you can inject a Kotlin class reference and use that in your Java class and Vice-versa.
This might help: https://kotlinlang.org/docs/tutorials/mixing-java-kotlin-intellij.html
I hope that clears the doubt.
Upvotes: 2