【问题标题】:Kotlin: Implement generic Interface multiple times with different Subclasses (Base Class is Constraint)Kotlin:使用不同的子类多次实现泛型接口(基类是约束)
【发布时间】:2019-02-07 20:10:27
【问题描述】:

错误消息:“SchedulableInserter”的类型参数 E 的值不一致:事件、分配

所以基本上我有一个抽象类 Schedulable。 我也有两个类事件(单一发生的事件,如时间戳) 和一个班级作业(基本上是一个事件,但也有一个持续时间) 我有一个 MainActivity,我想在其中将实例插入 SQLiteDB。 我想为 Schedulable 的每个子类使用不同的插入方法 轻松处理它们之间的差异。

//SchedulableInserter.kt

interface SchedulableInserter<E> where E : Schedulable{
        fun onInsertSchedulable(item:E)
}

//MainActivity.kt

class MainActivity() : AppCompatActivity(),
    NavigationView.OnNavigationItemSelectedListener,
    SchedulableInserter<Incident>, SchedulableInserter<Assignment> {
 /* ^                                ^
    |                                |
   Sadly Kotlin says:
   Type parameter E of 'SchedulableInserter' has inconsistent values: 
   Incident, Assignment
   A Supertype apperars twice
*/
}

我的意思是,如果我将 SchedulerInserter 绑定到 Schedulable,我可以在方法中进行区分,但我希望不必这样做。

【问题讨论】:

  • 看起来像泛型和类型擦除的问题。你不能有两种不同的 SchedulableInserter&lt;&gt; 超类型,因为它们相互冲突,即使一个是 &lt;Incident&gt; 而另一个是 &lt;Assignment&gt;

标签: android generics kotlin constraints


【解决方案1】:

我的建议是将插入器作为 Activity 中的属性而不是实现的接口:

class MainActivity() : AppCompatActivity(),
    NavigationView.OnNavigationItemSelectedListener {
    val incidentInserter = SchedulableInserter<Incident> { ... }
    val assignmentInserter = SchedulableInserter<Assignment> { ... }
}

要使that syntax 可用,currently 需要在 Java 中而不是 Kotlin 中定义 SchedulableInserter;否则你必须写

    val incidentInserter = object : SchedulableInserter<Incident> { 
        override fun ...
    }

【讨论】:

  • 我们如何使用这些对象??
  • 你能提供更多的上下文吗?没有它,我只能回答“就像你使用任何对象一样,它们没有什么特别之处”。
【解决方案2】:

由 Ben P 回答。

解决方案:

我的意思是如果我绑定,我可以在方法中区分 SchedulerInserter 到 Schedulable,但我希望不必这样做 这样做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    • 1970-01-01
    • 2015-04-05
    • 2012-06-29
    • 2011-09-07
    • 1970-01-01
    相关资源
    最近更新 更多