Skip to content

Instantly share code, notes, and snippets.

@junoatwork
Created August 3, 2020 19:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save junoatwork/c5be38dfd0d5afec379035c13cec0dc7 to your computer and use it in GitHub Desktop.
Save junoatwork/c5be38dfd0d5afec379035c13cec0dc7 to your computer and use it in GitHub Desktop.
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