我原谅了Kotlin中有关匕首的简单代码,但它在运行时不起作用。有什么问题以及如何更新此代码?
我有一个Notification类,我想执行'runNotification'。
interface Notifications { fun runNotification() } class NotificationsImpl @Inject constructor( private val context: Application ) : Notifications { override fun runNotification() { Log.e("Notifications", "runNotification") } }
NotificationModule.kt
@Module class NotificationModule { @Provides @Singleton fun providerNotifications(notificationsImpl: NotificationsImpl): Notifications = notificationsImpl }
ApplicationComponent.kt
@Singleton @Component(modules = [NotificationModule::class]) interface ApplicationComponent { @Component.Builder interface Builder { @BindsInstance fun application(application: Application): Builder @BindsInstance fun notificationModule(notificationModule: NotificationModule): Builder fun build(): ApplicationComponent } fun inject(application: Application) }
应用程序中的代码
DaggerApplicationComponent.builder() .application(this) .notificationModule(NotificationModule()) .build() .inject(this)
代码测试(此代码“通知”返回为NULL):
class MainActivity : AppCompatActivity() { @Inject lateinit var notifications: Notifications override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) notifications.updateNotification() } }
等级:
implementation "com.google.dagger:dagger:2.17" kapt "com.google.dagger:dagger-compiler:2.17" implementation "com.google.dagger:dagger-android:2.17" kapt "com.google.dagger:dagger-android-processor:2.17" kapt "com.google.dagger:dagger-android-support:2.17"