简体   繁体   中英

Kotlin: Implement generic Interface multiple times with different Subclasses (Base Class is Constraint)

Error Msg: Type parameter E of 'SchedulableInserter' has inconsistent values: Incident, Assignment

So basically I have an abstract class Schedulable. Also I have two classes Incident (Single occuring event, like a timestamp) and a class Assignment(Basically an Incident but with a duration too) I have a MainActivity, where I want to insert Instances into a SQLiteDB. I want to have a different insert-method for every subclass of Schedulable to easily handle the differences between them.

//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
*/
}

I mean I could differentiate within the method if i bind SchedulerInserter to Schedulable, but I would appreciate not having to do that.

What I'd suggest is having the inserters as properties in the activity instead of implemented interfaces:

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

To make that syntax available you currently need to define SchedulableInserter in Java instead of Kotlin; otherwise you have to write

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

Answered by Ben P.

Solution:

I mean I could differentiate within the method if i bind SchedulerInserter to Schedulable, but I would appreciate not having to do that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM