I am not able to understand and I couldn\'t find the meaning of out keyword in kotlin.
You can check example here:
List
>
With this signature:
List
you can do this:
val doubleList: List = listOf(1.0, 2.0)
val numberList: List = doubleList
which means T is covariant:
when a type parameter T of a class C is declared out, C
can safely be a supertype of C .
This is contrast with in, e.g.
Comparable
you can do this:
fun foo(numberComparable: Comparable) {
val doubleComparable: Comparable = numberComparable
// ...
}
which means T is contravariant:
when a type parameter T of a class C is declared in, C
can safely be a supertype of C .
Another way to remember it:
Consumer in, Producer out.
see Kotlin Generics Variance
-----------------updated on 4 Jan 2019-----------------
For the "Consumer in, Producer out", we only read from Producer - call method to get result of type T; and only write to Consumer - call method by passing in parameter of type T.
In the example for List
, it is obvious that we can do this:
val n1: Number = numberList[0]
val n2: Number = doubleList[0]
So it is safe to provide List
when List
is expected, hence List
is super type of List
, but not vice versa.
In the example for Comparable
:
val double: Double = 1.0
doubleComparable.compareTo(double)
numberComparable.compareTo(double)
So it is safe to provide Comparable
when Comparable
is expected, hence Comparable
is super type of Comparable
, but not vice versa.