I have a ```class Foo<out T>``` I need to cr...
# getting-started
c
I have a
Copy code
class Foo<out T>
I need to create a function
Copy code
fun <T> Foo<T>.foo(o: Foo<T>)
that function should NOT compile if the two
T
are different. As it is, it does compile because
T
is inferred to
Any?
. Currently, I use
@OnlyInputTypes
, but that's very brittle and I'd prefer to migrate to something more stable. I have tried
Copy code
fun <T, R : T> Foo<T>.foo(o: Foo<R>)
but
T
also gets inferred to
Any?
. Is there another way to declare that constraint?
s
not even
inline fun <reified T> Foo<T>.foo(o: Foo<T>)
helps, so I guess there's no way to circumvent the type earasure 🤔 Playground: https://pl.kotl.in/fu_l-9sUZ I guess you could write a compiler plugin or maybe even KSP is powerful enough.
a
reified T at least prints a compiler warning TYPE_INTERSECTION_AS_REIFIED_WARNING
c
Yeah that's better than nothing.
It won't work for Java users, but
@OnlyInputTypes
doesn't either anyway
The only solution I can think of is making
foo()
a member of
Foo
(instead of an extension), but that is not feasible in my case
a
it's not nice to use an internal type, but
@kotlin.internal.Exact
triggers "Argument type mismatch" error https://pl.kotl.in/G3bbKPUjv
c
Ah, do you know what the difference is between
@OnlyInputTypes
and
@Exact
?
I've used
@OnlyInputTypes
because that's what
assertEquals
uses
The error message is actually much better with
@Exact
, maybe I should migrate to it 🤔
Ah no I can't use
@Exact
, because it refuses subtypes of
T
, which
@OnlyInputTypes
doesn't
y
Is
@OnlyInputTypes
that brittle? It feels safer to me than a compiler plugin. Also, if it ever doesn't work, then it's as if it wasn't there. I'm talking btw about shadowing it in your own module so that you have access to it, not on about error suppression (which is a bad idea)
c
Is
@OnlyInputTypes
that brittle? It feels safer to me than a compiler plugin.
I've had issues before when it broke during an upgrade.
I'm talking btw about shadowing it in your own module so that you have access to it,
That doesn't work anymore. I think it broke with K2, I don't remember.
not on about error suppression (which is a bad idea)
…I knoooow… 😕