Last active
July 19, 2018 20:58
-
-
Save subinkrishna/4bfb2b59b66b1e56d6f6fc79a1ebc4ed to your computer and use it in GitHub Desktop.
[extends vs super] #java #generics #kotlin
This file contains hidden or 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
import java.util.ArrayList; | |
import java.util.List; | |
public class JavaGenericsTest { | |
public static void main(String[] args) { | |
List<? super B> l1 = new ArrayList<A>(); | |
// l1.add(new A()); // Nope! | |
l1.add(new B()); | |
l1.add(new C()); | |
List<? extends A> l2 = new ArrayList<B>(); | |
// NOPE - No write! | |
// l2.add(new A()); | |
// l2.add(new B()); | |
// l2.add(new C()); | |
List<A> l3 = new ArrayList<A>(); | |
l3.add(new A()); | |
l3.add(new B()); | |
l3.add(new C()); | |
} | |
static class A {} | |
static class B extends A {} | |
static class C extends B {} | |
} |
This file contains hidden or 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
object KotlinGenericsTest { | |
@JvmStatic | |
fun main(args: Array<String>) { | |
val a = ArrayList<A>() | |
val b = ArrayList<B>() | |
copy(a, b) | |
val c: ArrayList<in B> = a | |
// c.add(A()) // Nope! | |
c.add(B()) | |
c.add(C()) | |
} | |
fun <T> copy(dest: MutableList<in T>, src: List<T>) { | |
for (i in src.indices) | |
dest[i] = src[i] | |
} | |
open class A | |
open class B : A() | |
class C : B() | |
} |
This file contains hidden or 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
fun main(args: Array<String>?) { | |
// in - for consumers | |
// Can take the type and it's parent types | |
var a: X<in B> | |
a = Y<A>() | |
a = Y<B>() | |
// a = Y<C>() // Error! | |
// out - for producers | |
// Can take the type and it's sub types | |
var b: X<out B> | |
// b = Y<A>() // Error! | |
b = Y<B>() | |
b = Y<C>() | |
} | |
interface X<T> | |
class Y<T> : X<T> | |
open class A | |
open class B : A() | |
class C : B() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment