Nullable contravariant

Hi,

I can’t grasp how to get this compiling
class Foo() {
fun doit(t: Foo): Unit {}
}

val a = Foo<Int?>().doit(Foo<Int>())

I have been trying the ‘out’ contravariance, but nothing works.

First of all out keyword coresponds to covariance, not contravariance :wink: I’m not sure what you plan to implement as a whole, but to make this snippet compile you can write this:

class Foo<T> {
	fun doit(t: Foo<out T>) = Unit
}

val a = Foo<Int?>().doit(Foo<Int>())
2 Likes

Thanks. That clarifies a lot.
Thanks for the swift response.

It seems so obvious now. The documentation page doesn’t enough cover generics being used in method parameters IMHO.

2 Likes