Created
August 3, 2020 19:45
-
-
Save junoatwork/c5be38dfd0d5afec379035c13cec0dc7 to your computer and use it in GitHub Desktop.
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
class A<out T>(val value: T) | |
class B<T>(val value: T) | |
fun <T> doA(a: A<T>, t: T): T = t | |
fun <T> doB(b: B<T>, t: T): T = t | |
fun <T> doA2(a: A<T>) = fun (t: T): T = t | |
init { | |
// this compiles, because T is inferred to be "Any", because A specifies that T is covariant ("out") | |
// which triggers a "race to the top" for the broadest possible type | |
val x1 = doA(A(12), "str") | |
// to get the behavior that we actually want, whch is to restrict the second parameter based on the first parameter, | |
// we'd need to ensure T was never covariant | |
val x2 = doB(B(12), "str") | |
// but if we can't change the interface (e.g. it's a builtin), we can interrupt the type inference | |
// by breaking it up into two function calls, e.g. by currying | |
val x3 = doA2(A(12))("str") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment