In his talk Compilers are Databases, Martin Odersky presents an interesting variance corner case:
class Tree[-T] {
def tpe: T @uncheckedVariance
def withType(t: Type): Tree[Type]
}
T
is defined to be contravariant, because it is useful to think of a typed tree (Tree[Type]
) as a subtype of an untyped tree (Tree[Nothing]
), but not the other way around.
Normally, the Scala compiler would complain about T
appearing as the return type of the tpe
method. That's why Martin shuts up the compiler with an @uncheckedVariance
annotion.
Here is the example translated to Kotlin:
abstract class Tree<in T> {
abstract fun tpe(): T
abstract fun withType(t: Type): Tree<Type>
}
As expected, the Kotlin compiler complains about T
appearing in an 'out' position.
Does Kotlin have something similar to @uncheckedVariance
?
Or is there a better way to solve this particular problem?
Kotlin has an @UnsafeVariance
annotation which is an equivalent to @uncheckedVariance
in scala:
abstract class Tree<in T> {
abstract fun tpe(): @UnsafeVariance T
abstract fun withType(t: Type): Tree<Type>
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With