LoginSignup
0
0

More than 3 years have passed since last update.

dagger2入門 - basic(@Module & @Provides)

Posted at

概要

詳細

@Injectなしの基本クラスを定義する

class Age {
    fun myAge(): String {
        return "22"
    }
}

abstract class Citer {
    abstract fun doWhat(): String
}

class Student(val age: Age) {
    fun doWhat(): String {
        return age.myAge()
    }
}

class Worker : Citer() {
    override fun doWhat(): String {
        return "work"
    }
}

モジュールで上記のクラスを導入する

@Module
class CiterModule {
    @Provides
    fun provideAge(): Age {
        return Age()
    }
    @Provides
    fun providedStudent(age: Age): Student {
        return Student(age)
    }

    @Provides
    fun providedWorker(): Worker {
        return Worker()
    }
}

コンポネントを定義するときに、モジュールを導入する

@Component(modules = [CiterModule::class])
interface CiterComponent {
    fun inject(house: House)
}

同じ方法で注入する

class House {
    @Inject
    lateinit var student: Student

    @Inject
    lateinit var worker: Worker

    init {
        DaggerCiterComponent.create().inject(this)
    }

    fun showTime() {
        println(student.doWhat())
        println(worker.doWhat())
    }
}

fun main(args: Array<String>) {
    val house = House()
    house.showTime()
}

結果

22
work

Process finished with exit code 0

遷移図

スクリーンショット 2019-12-21 16.33.34.png

サンプルコード

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