Created
May 12, 2021 09:11
-
-
Save channyeintun/5f663ae97bc5a9de429e199d59dfc719 to your computer and use it in GitHub Desktop.
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
| package main | |
| //Covarient example start | |
| interface Source<out T> { | |
| fun nextT(): T | |
| } | |
| class Complement<Int>(var num:Int):Source<Int>{ | |
| override fun nextT()=num | |
| override fun toString()="${this::class.simpleName}" | |
| } | |
| fun demo(num: Source<Int>) { | |
| val objects: Source<Any> = num // This is OK, since T is an out-parameter)(Out means covarient) | |
| println(objects) | |
| println(objects.nextT()) | |
| }//covarient example end | |
| //Contravariant | |
| interface Comparable<in T> {// in means contravarient | |
| operator fun compareTo(other: T): Int | |
| } | |
| fun demo2(x: Comparable<Number>) { | |
| println(x.compareTo(1.0)) // 1.0 has type Double, which is a subtype of Number | |
| // Thus, you can assign x to a variable of type Comparable<Double> | |
| val y: Comparable<Double> = x // OK! | |
| println(y) | |
| } | |
| class Complement2<Number>(var num:Int):Comparable<Number>{ | |
| override fun compareTo(other:Number)=0 | |
| } | |
| //Contravariant end | |
| fun main(){ | |
| demo(Complement<Int>(123)) | |
| demo2(Complement2<Number>(2)) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment