It's easy to get lost in the `<?>` stuff :si...
# getting-started
k
It's easy to get lost in the
<?>
stuff simple smile
@gabrielfv Let's start a thread.
g
I'm thinking that maybe I might create a wrapper to the producer
k
What you're doing looks fine to me, I'll give it a shot myself.
Do you happen to control the producer and consumer classes?
g
Neither of them are mine, I wan't to make call-site filtering for convenience
I was thinking of creating my own Producer that filters that before notifying, so I don't need to control the cosumer (at least I hope so)
k
Hmm just removing
in
works for me:
Copy code
fun <T: Any> Producer<T?>.consume(consume: (T) -> Unit) {
	attachConsumer { it?.let(consume) }
}
(and adding the
?
, I'm not sure why that is missing)
☝️ 1
g
Oh omg
It works, indeed. I was overcomplicating things a lot
It also goes to show that I'm not too aware of how to use projection as of yet
k
Sidenote: I'd name the function something different,
attachConsumerDropNulls
or something. It's easy to forget values are silently being dropped here when using this.
g
Yes, I agree, the real name is
observeNonNulls()
k
Allright, just making sure.
g
Looking at it, if we claim that our producer is of
T?
, wouldn't it make setting our upper bound of
T
to
Any
redundant?
I believe the compiler could infer from that
T?
that the upper bound
Any?
doesn't make sense, and make it
Any
.
k
Nope, it doesn't do that.
g
The linter doesn't say anything, but It works just the same way.
Or someone is lying, because my lambda still receives non-nulls
And I'm still able to explicitly make
<T : Any?> ... <T?>
. That's interesting.
k
Well in this particular case it indeed doesn't matter, but it's not the same. Try for example
prod.consume<String?> {  }
.
g
Oh yes, indeed. Let me see if I got it then: making
<T> ... <T?>
will tell the compiler that my consumer can both consume nullable types or not, whereas my producer will always produce nullable.
And
<T : Any>
will assert that my consumer will never be consuming nullables.
That means that
<T> ... <T?>
only worked for me because my producer was of
T!
, but if it was
T?
, the compiler wouldn't be able to infer it alike. Gotta give it a try Gave it a try: It still infers the non-null variant.
k
Yes! In this particular case though, a function type in Kotlin has declaration site variance on the parameter type so a parameter that accepts nullable arguments or indeed
Any?
would be fine too. That why it doesn't matter in this case.
Copy code
package kotlin.jvm.functions

public interface Function1<in P1, out R> : kotlin.Function<R> {
    public abstract operator fun invoke(p1: P1): R
}
g
Great. That was very helpful, thanks!
k
You're welcome!