有没有办法使用注释@Binds而不是@Provides与返回类型需要参数

问题描述 投票:1回答:2

任何可能的使用方式使用绑定注释提供此?

@Singleton
@Provides
fun provideUtils(context: Context): Utils {
    return Utils(context)
}
android kotlin dagger-2
2个回答
0
投票

如果你的Utils类有一个@Inject构造函数,例如

class Utils @Inject constructor(private val context: Context) {
    // ...
}

...然后你可以像这样绑定它,Dagger应该能够弄清楚如何创建它(假设你在某处提供了Context):

@Singleton
@Binds
fun bindUtils(utils: Utils): Utils

0
投票

你应该在这里使用构造函数注入。如果使用构造函数注入,则不需要@Provides@Binds

@Singleton // scope on the class
class Utils @Inject constructor(private val context: Context)

就这样。

© www.soinside.com 2019 - 2024. All rights reserved.