0
votes

In Kotlin i am learning about covariant(a subtype can be used in place of a super type). They wrote there something like a rule. but it seems wrong for me. It is written:

You can’t, however, use out if the class has function parameters or var properties of that generic type.

But i think that the word or should be replaced with the word and, because in situation when a class has a function that "gets" the type as a parameter, if the property of the generic type is a val and not var, and damage can't be done, because any assignment isn't possible to val property. Am i right or what is written in the book is correct and i'm missing something?

Edit: I just realized (according to some post i saw in this forum) that the only situation that a parameter can be a problem although property is declared as val, is in case we have a container of type T, let's say List then it may be a problem if we try to add to the List, but if we don't have a container i can't see situation when getting a parameter type can make trouble while property is val. Am i right?

1

1 Answers

0
votes

The out keyword is for covariance, not contravariance.

Here's a basic example of the trouble caused in an imaginary class where covariance is allowed for the var property type:

class Container<out T>(var item: T)

val intContainer = Container<Int>(1)
val numberContainer: Container<Number> = intContainer // cast is allowed for covariant type
numberContainer.item = 5f // allowed if item is a var
val intValue = intContainer.item // Float value is cast to an Int!

This isn't possible with a val so the above class could be covariant at the declaration site if item were a val.