Last active
October 29, 2023 12:36
-
-
Save MaksimDmitriev/6d4e623690d5453babaf647403f3cc91 to your computer and use it in GitHub Desktop.
Java generics and Kotlin in/out
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Why are Java generics invariant? | |
// invariant means List<Object> is NOT a parent of List<String>. | |
// if it was the case, then: | |
List<String> strs = new ArrayList<String>(); | |
List<Object> objs = strs; // !!! A compile-time error here saves us from a runtime exception later. | |
objs.add(1); // Put an Integer into a list of Strings | |
String s = strs.get(0); // !!! ClassCastException: Cannot cast Integer to String |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ru.maksim.sample; | |
interface MyCollection<E> { | |
// void addAll(MyCollection<E> items); | |
void addAll(MyCollection<? extends E> items); | |
} | |
package ru.maksim.sample; | |
public class Client { | |
void copyAll(MyCollection<Object> to, MyCollection<String> from) { | |
to.addAll(from); | |
// since "to" expects an instance of MyCollection<Object> and | |
// MyCollection<String> is not a child of MyCollection<Object> | |
// "? extends E" needs to be used. | |
} | |
} | |
public class Client { | |
void copyAll(MyCollection<Number> to, MyCollection<Double> from, MyCollection<Integer> from2) { | |
// since "to" expects an instance of MyCollection<Number> and | |
// MyCollection<Double> is not a child of MyCollection<Number> | |
// "? extends E" needs to be used. | |
to.addAll(from2); | |
to.addAll(from); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment