Is it possible for me to do something like that? `...
# getting-started
g
Is it possible for me to do something like that?
Copy code
fun <T : Any> Producer<in T>.consume(consume: (T) -> Unit) {
    attachConsumer(Consumer<T?> { it?.let(consume) })
}
The producer is a Java class that is null-unsafe, and I want to be able to consume it on a null-safe manner, filtering out any possible nulls, and having my consuming function only see non-null values. If I don't tell that my producer is contravariant in the expected type, I have to manually call it like
consume<MyType>
, otherwise my lambda will receive a
MyType!
. If I try the above, however, I'll get an error: "Required: Consumer<Any?>, Found: Consumer<T?>". Shouldn't
Consumer<T?>
be acceptable as a
Consumer<Any?>
? Or am I completely lost in generic typing?