我想使用Dagger 2提供一个函数作为依赖项:
@Module
class DatabaseModule {
@Provides
@Singleton
fun provideDatabase(application: Application, betaFilter: (BetaFilterable) -> Boolean): Database {
return Database(application, BuildConfig.VERSION_CODE, betaFilter)
}
@Provides
@Suppress("ConstantConditionIf")
fun provideBetaFiler(): (BetaFilterable) -> Boolean {
return if (BuildConfig.FLAVOR_audience == "regular") {
{ it.betaOnly.not() }
} else {
{ true }
}
}
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,它似乎不起作用:
[dagger.android.AndroidInjector.inject(T)] kotlin.jvm.functions.Function1<?
super com.app.data.BetaFilterable,java.lang.Boolean>
cannot be provided without an @Provides-annotated method.
Run Code Online (Sandbox Code Playgroud)
我在这里想念什么?
android functional-programming dependency-injection kotlin dagger-2
我目前正在使用 kotlin 开发一个多平台模块。为此,我依赖expect/actual机制。
我声明了一个简单的类Common.kt:
expect class Bar constructor(
name: String
)
Run Code Online (Sandbox Code Playgroud)
我想在通用方法中使用定义的类(也存在于 中Common.kt):
fun hello(bar: Bar) {
print("Hello, my name is ${bar.name}")
}
Run Code Online (Sandbox Code Playgroud)
实际实现定义在Jvm.kt:
actual data class Bar actual constructor(
val name: String
)
Run Code Online (Sandbox Code Playgroud)
问题是我的hello函数中出现以下错误
未解决的参考:名称
我究竟做错了什么?
在Swift中,我们可以定义一个可以由a class或struct基于条件符合的协议:
protocol AlertPresentable {
func presentAlert(message: String)
}
extension AlertPresentable where Self : UIViewController {
func presentAlert(message: String) {
let alert = UIAlertController(title: “Alert”, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: “OK”, style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
Run Code Online (Sandbox Code Playgroud)
该AlertPresentable协议受到限制,只能通过一致UIViewController.有没有办法在Kotlin中获得相同的结果?
我正在开发一个具有 dagger 依赖项的 Android 应用程序。当通过构造函数注入注入类时,它会抛出一个找不到符号的错误。如果我通过@Provides模块内部定义的方法提供依赖项,则一切正常。
编码:
public class SixthGenericTest {
@Inject
FirstTest firstTest;
@Inject
public SixthGenericTest()
{
Injection.create().getAppComponent().inject(this);
}
public String getData(){
return firstTest.getTestName();
}
}
@Singleton
@Component(modules = {FirstModule.class})
public interface AppComponent {
void inject(SixthGenericTest sixthGenericTest);
}
Run Code Online (Sandbox Code Playgroud)
和我得到的错误:
错误:(19, 28) 错误:找不到符号方法injectMembers(MembersInjector,SixthGenericTest)
我想在线程内执行任务并编写了以下代码:
Thread().run {
Log.i("TEST", "in thread")
Thread.sleep(5000);
transactionStatus = ApiFactory.getInstance().transactionService.abortTransaction()
synchronized(TestTransactionPayAbort.lock) {
TestTransactionPayAbort.lock.notify()
}
}
Log.i("TEST", "main")
synchronized(TestTransactionPayAbort.lock) {
TestTransactionPayAbort.lock.wait()
}
Run Code Online (Sandbox Code Playgroud)
根据调试器的说法,在执行之前Thread().run{},我位于线程 4 内。执行之后Thread.sleep(),调试器告诉我线程 4 正在休眠,而我原本期望看到线程 5 正在休眠。关于Log():我立即在线程和主线程中看到: 5秒后
我在这里犯了什么错误?