LoginSignup
16
14

More than 5 years have passed since last update.

AndroidでKotlinを使ったDagger2

Last updated at Posted at 2016-04-14

AndroidでKotlinを使ったDagger2

ハマったので、共有します。
Android Studio 2.0でも動きます
サンプル:https://github.com/kamedon/AS2KotlinDagger2

追記。。。
Submoduleまで使ったサンプルなのに、push忘れてて古いバージョンだ。。。。
あとでソースを更新しておきます。。。。。。
ごめんなさい
追記
SubmoduleとScopeを新たに追加してPushしました。
ActivityScopeがちゃんとできてるっぽい!

KotlinでDagger2を使う

app/build.gradleにDagger2を設定

重要な部分のみ抜粋
全文https://github.com/kamedon/AS2KotlinDagger2/blob/master/app/build.gradle

kapt {
    generateStubs = true
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"

    compile 'com.google.dagger:dagger:2.2'
    kapt 'com.google.dagger:dagger-compiler:2.2'
    provided 'org.glassfish:javax.annotation:10.0-b28'
}

エラー

たくさんエラーがでて困ったので共有します

Dagger2のバージョン

compile 'com.google.dagger:dagger:2.+'
ってずっとしてたんですが、2.3だと以下のエラーが出てビルドができない!

Error:Execution failed for task ':app:compileDebugJavaWithJavac'. >java.lang.NoSuchMethodError: >com.google.common.collect.ImmutableSetMultimap$Builder.putAll(Ljava/lang/Iterable;)Lcom/google/common/collect/ImmutableSetMultimap$Builder;

どうもAppComponentの @Component(modules = arrayOf(AppModule::class)) でエラーがでるようだ
daggar2.2 -> 2.3 の時に発生したエラーのようだ。。。
参考:https://github.com/google/dagger/issues/356

@Namedができない

Moduleの中で同じ型を@Providesするとエラーになるので@Namedをつけて識別するですが
MainActivityの中で、以下のように記述してました。。。

@Inject @Named("Toast")
lateinit var toast: PrintInterface

Error:com.example.kamedon.sample20.print.PrintInterface cannot be provided >without an @Provides- or @Produces-annotated method. >com.example.kamedon.sample20.MainActivity.print [injected field of type: >com.example.kamedon.sample20.print.PrintInterface print]
というエラーが出る

どうもKotlinでのアノテーションのつけたが間違っていた。
これにだいぶ時間をくった
正しく以下の通り

@field:[Inject Named("Toast")]
lateinit var toast: PrintInterface

@Named @Injectって書くとget set field全部にアノテーションの設定がつくのかな
なので、きちんと指定しないといけないっぽい

これでKotlinで幸せDagger生活がおくれるのかしら。。。

参考:
Annotations - Annotation Use-site Targets
https://kotlinlang.org/docs/reference/annotations.html

damianpetla/kotlin-dagger-example
https://github.com/damianpetla/kotlin-dagger-example
サンプルがあって本当に感謝。。。

16
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
14