Last active
December 23, 2019 07:15
-
-
Save bastman/7776bb2a58254c9b37cee4a4e0023ac3 to your computer and use it in GitHub Desktop.
kotlin generics playground
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
// The ins and outs of Kotlin: https://kotlin.christmas/2019/22 | |
// https://medium.com/@elye.project/in-and-out-type-variant-of-kotlin-587e4fa2944c | |
// https://kotlinlang.org/docs/reference/generics.html | |
// https://www.reddit.com/r/Kotlin/comments/dtfba1/covariance_vs_invariance/ | |
// https://i.imgur.com/oKD9hPL.png | |
// https://docs.google.com/document/d/13eRz9uu8EuAUagcwEvLDUoWYB7TOyMgJWJyFLJnSB10/ | |
// https://typealias.com/guides/ins-and-outs-of-generic-variance/ | |
data class In<out T:Number>(val c:T) | |
data class Out<out E>(val c:E) | |
fun <R:Number?> foo(c:R): Out<R> { | |
val o = Out(c=c) | |
// return o - OK | |
val c2 = 1.0 | |
val o2 = Out(c2) | |
// return o2 // FAILS | |
val c3 = 1.0 as R | |
val o3 = Out(c3) | |
//return o3 // OK | |
//val c4 = 1.0 as? R? | |
val o4 = Out(null as R) | |
return o4 // OK | |
} | |
fun main() { | |
val a:Double? = null | |
val out = foo(a) | |
println(out) | |
// In(1.0) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment