LoginSignup
1
1

More than 3 years have passed since last update.

Kotlinでinterfaceの実装を分ける場合は委譲を利用する

Last updated at Posted at 2019-11-27

問題

以下のようなRepositoryをinterfaceとして定義したとする。

interface HogeRepository {
    suspend fun hoge()
}

さらに先のRepositoryが次のように実装され本番で運用されていたとする。

class HogeRepositoryProduction : HogeRepository {
    override suspend fun hoge() = withContext(Dispatchers.IO) {..}
}

また、開発時にローカル上から固定値を返したい場合があり、次のようなRepositoryも実装していたとする。

class HogeRepositoryDevelopment : HogeRepository {
    override suspend fun hoge() {..}
}

このとき HogeRepository へ追加があった場合などにどちらのRepositoryにもその実装が必要になり少し面倒くさい。

解決策

先の問題をKotlinの class delegation を利用し解決することができます。今回の例では、HogeRepositoryDevelopmentHogeRepository 実装を HogeReposiyoryProduction に任せるようにします。

class HogeRepositoryDevelopment(
        private val production: HogeRepositoryProduction
) : HogeRepository by production

このようにすることで HogeRepository の実装を委譲することで HogeRepositoryDevelopment は、必要な個所だけ上書きすればよくなり、interfaceに変更があっても本番用のみ変更を加えるだけでよくなります。

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