Dagger2预选赛没有与Kotlin合作?

时间:2018-02-01 14:20:59

标签: android kotlin dagger-2

我有一个简单的课程如下

class MainString(val msg: String)

我想为它注入不同的参数,所以我按https://google.github.io/dagger/users-guide

中所示的指南使用@Named限定符

我的AppModule已经

@Provides @Named("Two")
fun provideTwoMainString(): MainString {
    return MainString("Two")
}

@Provides @Named("One")
fun provideOneMainString(): MainString {
    return MainString("One")
}

在我的MainActivity中,我只是致电

@Inject @Named("One")
lateinit var stringOne: MainString

@Inject @Named("Two")
lateinit var stringTwo: MainString

然而,当我编译时,它会抱怨

Error:(11, 1) error: com.elyeproj.demo_dagger_scope.MainString cannot be provided without an @Inject constructor or from an @Provides- or @Produces-annotated method.

似乎要我提供另一个没有限定符的提供者。因此,如果我添加以下内容,则所有内容都将编译。但它并不适合我,因为我想要注入不同的参数。

@Provides
fun provideMainString(): MainString {
    return MainString("Solo")
}

我做错了什么?

3 个答案:

答案 0 :(得分:13)

注释工作在kotlin上略有不同。看this doc

您必须将该字段注释为:

@Inject @field:Named("Two")
lateinit var stringOne: MainString

答案 1 :(得分:0)

如果将以下内容添加到限定符批注中:

$ valgrind ./bin/matrix_cr_obtn
==10251== Memcheck, a memory error detector
==10251== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==10251== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==10251== Command: ./bin/matrix_cr_obtn
==10251==
enter number of rows: 5
enter number of cols: 3
    0    0    0
    0    0    0
    0    0    0
    0    0    0
    0    0    0
==10251==
==10251== HEAP SUMMARY:
==10251==     in use at exit: 0 bytes in 0 blocks
==10251==   total heap usage: 6 allocs, 6 frees, 100 bytes allocated
==10251==
==10251== All heap blocks were freed -- no leaks are possible
==10251==
==10251== For counts of detected and suppressed errors, rerun with: -v
==10251== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

那么您就不必添加“字段:”

例如,使用:

@Target(FIELD, VALUE_PARAMETER, FUNCTION, PROPERTY_GETTER, PROPERTY_SETTER)

您可以进行如下注入:

  @Qualifier
  @Retention(RUNTIME)
  @Target(FIELD, VALUE_PARAMETER, FUNCTION, PROPERTY_GETTER, PROPERTY_SETTER)
  annotation class One

很遗憾, @Inject @One lateinit var stringOne: String 没有指定@Named,因此只需创建自己的注释即可。 @Target(..)绝对不是一个好主意,因为它使用的是字符串文字。

答案 2 :(得分:0)

1)如果您使用的是如下所示的限定词,则此处为'OmdbService'

@Qualifier
public annotation class OmdbService

然后使用

@Inject  @field:OmdbService lateinit var retrofitOmdbService: Retrofit

2)如果使用的是如下所示的命名提供程序,则此处为'orangeservice_retrofit'

@Provides
    @OrangeApplicationScope
    @Named("orangeservice_retrofit")
    fun retrofit(okHttpClient :OkHttpClient, gson : Gson, c :Context): Retrofit {
        return Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create(gson))
                .client(okHttpClient)
                .baseUrl(c.getString(R.string.base_url))
                .build()
}

然后使用

@Inject @field:Named("orangeservice_retrofit") lateinit var retrofitOrangeService: Retrofit
相关问题