What is out keyword in kotlin

后端 未结 5 1505
情深已故
情深已故 2021-01-30 06:20

I am not able to understand and I couldn\'t find the meaning of out keyword in kotlin.

You can check example here:

List
         


        
5条回答
  •  太阳男子
    2021-01-30 06:42

    Refer to thie manual of kotlin

    The Kotlin List type is an interface that provides read only operations like size, get and so on. Like in Java, it inherits from Collection and that in turn inherits from Iterable. Methods that change the list are added by the MutableList interface. This pattern holds also for Set/MutableSet and Map V>/MutableMap

    And this,

    In Kotlin, there is a way to explain this sort of thing to the compiler. This is called declaration-site variance: we can annotate the type parameter T of Source to make sure that it is only returned (produced) from members of Source, and never consumed. To do this we provide the out modifier:

    > abstract class Source {
    >     abstract fun nextT(): T }
    > 
    > fun demo(strs: Source) {
    >     val objects: Source = strs // This is OK, since T is an out-parameter
    >     // ... }
    

    The general rule is: when a type parameter T of a class C is declared out, it may occur only in out-position in the members of C, but in return C can safely be a supertype of C.

    In "clever words" they say that the class C is covariant in the parameter T, or that T is a covariant type parameter. You can think of C as being a producer of T's, and NOT a consumer of T's. The out modifier is called a variance annotation, and since it is provided at the type parameter declaration site, we talk about declaration-site variance. This is in contrast with Java's use-site variance where wildcards in the type usages make the types covariant.

提交回复
热议问题