LoginSignup
26
18

More than 5 years have passed since last update.

Dagger2の@Bindsの使い方

Last updated at Posted at 2016-11-28

Daggerを使う時、以下のようなコードをよく書くかと思います。

public interface IRepository {
    Item fetch();
}
public class RepositoryImpl implements IRepository {
    @Override
    public Item fetch() {
        // 何らかの実装
    }
}
@Module 
class Module {
    @Provides
    IRepository provideRepository(RepositoryImpl repository) {
        return repository;
    }
}

@Bindsを利用することで、上記と等価なコードを以下のように書くことができます。

@Modlule
abstract class Module {
    @Binds
    abstract IRepository provideRepository(RepositoryImpl repository);
}

前者と後者の違いをまとめると以下になります。

  • @Providesの代わりに@Bindsを利用していること
  • クラスとプロバイダメソッドがabstractであること

記述量が減るため、プロバイダメソッドを書くのが楽になります。
しかし、同一Module内に@Providesを利用したプロバイダメソッドを定義することはできないので、そこだけ注意が必要です。

26
18
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
26
18