Roman Nazarevych
Roman Nazarevych

Reputation: 7703

Usage of kotlin generics "in", "out" in inheritance

I have base class which I'm planning to use for downloading some data from server:

abstract class Processor<out T : BaseEntity> {
   fun loadData() {
      val data = fetchFromBackend()
      saveData(data)
   }

   // here I'll define specific logic of saving data
   // and here is my Error Type parameter T is declared as 'out' but occurs in 'invariant' position in type T
   abstract protected open fun saveData(data: T)

}

Then I have multiple implementation of this Processor class and use them like that

val processor: EntityProcessor<BaseEntity> = when(type){
               TypeA -> ProcessorImplementationA(...)
               TypeB -> ProcessorImplementationB(...)
               TypeC -> ProcessorImplementationC(...)

To be able to safely assign implementation of processor to base type I'm using out in T generic declaration. But this causes the problem in saveData(data: T) method. If I use invariance, means no keyword before generic declaration I will not be able to safely assign implementation of Processor to base type

Is there a way to implement this class hierarchy without class cast, or what is the best way to implement this?

Upvotes: 1

Views: 1950

Answers (1)

Yoni Gibbs
Yoni Gibbs

Reputation: 7018

Does this give you what you want?

abstract class Processor<T : BaseEntity> {...}

val processor: EntityProcessor<out BaseEntity> = ...

Upvotes: 3

Related Questions