Generics 带有泛型的Kotlin继承/声明

Generics 带有泛型的Kotlin继承/声明,generics,inheritance,kotlin,Generics,Inheritance,Kotlin,我正在尝试在RepoInit 1和2内启动RoomAlarmRepository 第一个说“类型不匹配”,不让我编译。也就是说,除非我像在RepoInit2中那样对其进行强制转换,此时它会告诉我强制转换未选中 class RepoInit1(app: App) { internal val repo: AlarmRepository<AlarmModel> = RoomAlarmRepository(app.database) } class RepoInit2(app: App)

我正在尝试在RepoInit 1和2内启动
RoomAlarmRepository

第一个说“类型不匹配”,不让我编译。也就是说,除非我像在
RepoInit2
中那样对其进行强制转换,此时它会告诉我强制转换未选中

class RepoInit1(app: App) {
internal val repo: AlarmRepository<AlarmModel> = RoomAlarmRepository(app.database)
}

class RepoInit2(app: App) {
internal val repo: AlarmRepository<AlarmModel> = RoomAlarmRepository(app.database) as AlarmRepository<AlarmModel>
}


class RoomAlarmRepository(val database: AppDatabase) : AlarmRepository<RoomAlarmModel> {

}

class RoomAlarmModel : AlarmModel {


}
类RepoInit1(app:app){
内部val repo:AlarmRepository

声明泛型类型,并使用
out
修饰符作为协变。 详情请参见此处

class RepoInit2(...) {
    internal val repo: AlarmRepository<out AlarmModel> = RoomAlarmRepository(...)
}
类RepoInit2(…){ 内部val repo:AlarmRepository=RoomAlarmRepository(…) }