Given I have the following code
interface Animal {}
class Cat() : Animal {}
class Dog() : Animal {}
class MyClass<B, A : List<B>>(val list1: A, val list2: A) {}
It looks like I can call the constructor with different list types like this:
val myClass = MyClass(listOf(Cat()), listOf(Dog()))
Is there a way to instruct the Kotlin compiler that both lists should have the same strict kind?
The goal is that I can call:
val myClass = MyClass(listOf(Cat()), listOf(Cat()))
val myClass = MyClass(listOf(Dog()), listOf(Dog()))
But I can't call:
val myClass = MyClass(listOf(Cat()), listOf(Dog()))
val myClass = MyClass(listOf(Dog()), listOf(Cat()))
Before you ask, the reason I need this is so I can implement two methods on MyClass
like this:
class MyClass<B, A : List<B>>(val list1: A, val list2: A) {
fun moreSameAnimals(list: A) = print("same")
fun <C : List<B> moreDifferentAnimals(list: C) = print("different")
}
And have the compiler chose the appropriate method depending on the single type of Animal
present in MyClass
MyClass<LinkedList<String>>
? If not, it is probably better to skipA
.moreSameAnimals
andmoreDifferentAnimals
. Again, it feels you differentiate on the type of the list, not type of animals. Feels a little like an XY problem. You explained what kind of code you would like to write, but you didn't really explain what kind of behavior you need. I suppose you already made some incorrect assumptions about generics, so the question is a little misleading.