Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Meaning of words "in" and "out" in Kotlin generics

I learn kotlin generics but naming makes me crazy.

Let consider 2 code snippets in java and in Kotlin which do the same job:

1. java

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    public void copy(List<? extends Number> from, List<? super Number> to) {
        assert from.size() == to.size();
        for (int i = 0; i < from.size(); ++i) {
            to.add(from.get(i));
        }
    }

Everything is clear.

from is a list of items of type which inherits from Number. So it could be List<Double> List <Short> etc. I understand why extends word is used

to is a list of items of type which is a supertype of Number. So it could List<Number> or List<Serializable> or List<Object>

2.Kotlin

The similar code for Kotlin:

    fun copy(from: Array<out Number>, to: Array<in Number>) {
        assert(from.size == to.size)
        for (i in from.indices)
            to[i] = from[i]
    }

From my point of view it looks counterintuitive.
Why Array<out Number> is Array of subtypes of Number ?

Why Array<in Number> is Array of supertypes of Number ?

I am sure creaters had some logic and I want to undesit.

>Solution :

Array<out Number> is an array you can get Numbers out of.

Array<in Number> is an array you can put Numbers in to.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading