August 2017
Intermediate to advanced
440 pages
10h
English
There is one important exception for the in and out position rules described in the previous section: constructor parameters are always invariant:
class Producer<out T>(t: T) // Usage val stringProducer = Producer("A") val anyProducer: Producer<Any> = stringProducer
The constructor is public, the type parameter T is declared as out, but we can still use it as a constructor parameter type at the in position. The reason is that a constructor method can't be called after an instance is created, so it is always safe to call it.
As we discussed in Chapter 4, Classes and Objects, we can also define a property directly in the class constructor using a val or var modifier. When covariance is specified, we can only define a ...
Read now
Unlock full access