Search code examples
kotlingenericscollectionskotlin-extensionkotlin-reified-type-parameters

Kotlin. How to set type of generic in runtime?


Is it possible to set type of filterIsInstance extension at runtime. For example I have list of Item and I nee to cast my list by specific condition:

fun (items: List<Item>) {
 items.filterIsInstance<if(someCondition) OldItem else NewItem>()
}

I understand that such code cannot work, but is it possible to do something like this in runtime, please help me.


Solution

  • These need to be separate branches of code anyway or there would be no reason to do this at runtime instead of compile time. Generic types are only useful at compile time to allow you to write code specific to a type. You would have to write it like this:

    fun (items: List<Item>) {
      if(someCondition) {
        val oldItems = items.filterIsInstance<OldItem>()
        // do something with old Items
      else {
        val newItems = items.filterIsInstance<NewItem>()
        // do something with new items
    }
    

    Or if you don't care about the type of the list after it's filtered, you could do this:

    fun (items: List<Item>) {
      val result: List<Item> = items.filter {
        if (someCondition) it is OldItem else it is NewItem
      }
    }