Home > Software engineering >  Kotlin. How to set type of generic in runtime?
Kotlin. How to set type of generic in runtime?

Time:11-30

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.

CodePudding user response:

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

CodePudding user response:

There's a version of filterIsInstance that takes a Class parameter, instead of using the generic type in the angle brackets:

fun <R> Iterable<*>.filterIsInstance(
    klass: Class<R>
): List<R>

So you could do

items.filterIsInstance(
    if(someCondition) OldItem::class.java
    else NewItem::class.java
)

But like the other answer says, if you're going to actually be working on them as that type, it probably makes more sense to have separate branches where you do the filtering and processing all as one type

  • Related