Is it possible to create a generic function which ...
# android
o
Is it possible to create a generic function which limits the type
T
to 2 different objects? For example, here we limit to type
Cat
or
Dog
something like(this is pseudocode):
Copy code
private fun<T : Cat or Dog> convertToIntArray(objects: List<T>) : IntArray {
    val objectIds = arrayListOf<Int>()
    objects.forEach {
        objectIds.add(it.id)
    }
    return objectIds.toIntArray()
}

// Then pass something like this:
val cats = convertToIntArray(oldListOfCats)
val dogs = convertToIntArray(oldListOfDogs)
k
I think you need to make
Cat
and
Dog
extend or implement some class/interface (
Animal
for example) and then you could use
where
something like that:
Copy code
private fun<T> convertToIntArray(objects: List<T>) : IntArray where T : Animal {
    val objectIds = arrayListOf<Int>()
    objects.forEach {
        objectIds.add(it.id)
    }
    return objectIds.toIntArray()
}
https://kotlinlang.org/docs/reference/generics.html
👍 2
o
Thank you @KamilH
b
If this is java, You need a wildcats symbol. fun<? extends Animal>. "Extends" means to implement the Animal Interface here. However, Kotlin has some nice ways to work around this. Check the generic page~