Ali
Ali

Reputation: 9994

Convert Static method in Dagger Module class to Kotlin

I have following project in Github : https://github.com/Ali-Rezaei/TMDb-Paging which I use Dagger2 for dependency injection.

One of my Module classes is as Follow in java :

@Module
public abstract class DetailModule {

    @FragmentScoped
    @ContributesAndroidInjector
    abstract DetailFragment detailFragment();

    @Provides
    @ActivityScoped
    static Movie provideMovie(DetailActivity activity) {
        return activity.getIntent().getExtras().getParcelable(EXTRA_MOVIE);
    }
}

As you can see provideMovie method is static. When I convert it to Kotlin :

@Module
abstract class DetailModule {

    @FragmentScoped
    @ContributesAndroidInjector
    internal abstract fun detailFragment(): DetailFragment

    companion object {

        @Provides
        @ActivityScoped
        internal fun provideMovie(activity: DetailActivity): Movie {
            return activity.intent.extras.getParcelable(EXTRA_MOVIE)
        }
    }
}

But when I build the project I get following Kotlin compiler error :

error: @Provides methods can only be present within a @Module or @ProducerModule
        public final com.sample.android.tmdb.vo.Movie provideMovie$app_debug(@org.jetbrains.annotations.NotNull()

Could be any solution to have the class in Kotlin?

Upvotes: 2

Views: 699

Answers (1)

Suryavel TR
Suryavel TR

Reputation: 3806

Comanion Object is technically different class and not annotated with @Module. (So you are getting that error)

you need to use JVM Annotations for methods. So Kotlin will create a static method inside DetailModule itself.

Try @JvmStatic

@Module
    companion object {
         @JvmStatic
         @Provides
         @ActivityScoped
         internal fun provideMovie(activity: DetailActivity): Movie {
             return activity.intent.extras.getParcelable(EXTRA_MOVIE)
         }
    }

Upvotes: 1

Related Questions