I can't wrap my head around why arent subtypes working with Kotlin generics.
Assume the following simple scenario
class Student : Person()
open class Person
This works
fun personOrStudent : Person{
return Student()
}
But this doesnt
fun <Item:Person> personOrStudent() : Item {
return Student()
}
I dont understand why. Isn't the return type Item , typed as a subtype of Person ? . I believe the syntax clearly communicates that Item would be a subtype of Person .
But I get a compile time error saying expected was Person , not a student.
Does this have something to do with covariance / contravariance?
CodePudding user response:
By defining a function as parameterized we basically mean that we don't know the exact type of Item
and that it depends on the call site. Student
may be a valid return value from this function, but it may be not.
Consider this example:
class NotAStudent : Person()
personOrStudent<NotAStudent>()
We expect that the function returns NotAStudent
, but implementation returned Student
. This is why it can't compile.
In other words: <Item: Person>
doesn't mean that Item
is just any Person
. It means Item
is a very specific subtype of Person
, but we don't know which one.