https://kotlinlang.org logo
Title
o

Ofir Bar

02/18/2020, 7:07 PM
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):
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

KamilH

02/18/2020, 7:14 PM
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:
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

Ofir Bar

02/18/2020, 7:15 PM
Thank you @KamilH
b

BrianZhang

02/21/2020, 4:14 PM
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~