Reputation: 1414
I have the below
open class Model
class WorkOrder : Model()
//An interface
interface ViewInterface<T : Model> {
fun notifyDataSuccessful(model: T?, models:ArrayList<T>?)
}
class WorkOrderSystemImpl(val viewInterface: ViewInterface<Model>) {
fun doSomething() {
val workOrders: ArrayList<WorkOrder> = ArrayList()
//the below line complains of type mismatch
viewInterface.notifyDataSuccessful(workOrders)
}
}
It complains of type-mismatch which is quite strange to me, because WorkOrder is a sub-type of Model and i'd expect it to resolve to same type.
Upvotes: 1
Views: 74
Reputation: 4294
It's about the Generics
's invariant
& covariant
, see Kotlin docs here.
In short, you can just remember:
Consumer in, Producer out!
which the Consumer
& Producer
is determined from the List
's view, that means you should think about the role of you List
, is it aConsumer
or Producer
? In your case, the models:ArrayList<T>?
is a Producer
, because it will be used by the implementation of ViewInterface
, so you should define the ViewInterface
like this:
interface ViewInterface<T: Model> {
fun notifyDataSuccessful(model: T?, models: ArrayList<out T>?)
}
Upvotes: 1