Is there any way to hint the compiler that it shou...
# compiler
p
Is there any way to hint the compiler that it should not infer
Any
in
fun <T> assertEquals(expected: T, result: T): Unit
when expected and result don’t have a shared ancestor?
s
expected and result have to be the exact same type according to this function signature. T stands for a singular type here
s
But the compiler will just infer
Any
for
T
when calling
assertEquals("one", 1)
, right?
d
You can use
OnlyInputTypes
annotation It is internal, but quite stable, and we are considering making it public
Copy code
@Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE")
fun <@kotlin.internal.OnlyInputTypes T> assertEquals(expected: T, result: T): Unit {...}
😍 3
r
That's cool! Nice too that you can make it compile by specifying the desired common super type:
assertEquals<Map<String, String>>(LinkedHashMap<String, String>(), TreeMap<String, String>())
Also nice that the compiler error tells you to do this: "Type inference failed. The value of the type parameter T should be mentioned in input types (argument types, receiver type or expected type). Try to specify it explicitly." (my emphasis) Perhaps a little late in the error message though.
p
yeah, hinting would work, but I’m doing a regex replace through the codebase and there’s no semantic inference possible 😄
The point is that the IDE notifies me of mismatches as I make changes so I can fix them, not the other way around
s
Once this is public we'd be able to apply it to kotest assertions too.
😍 4
p
Found the youtrack. Apparently it's being considered for 6 years now to be public. https://youtrack.jetbrains.com/issue/KT-13198
Yeah especially for kotest I have run in so many wrong test runs due to it allowing to expect different types to be equal. At least in tests you find it out quickly but I'd prefer these to not compile in the first place
s
I would add something like
fun <@OnlyInputTypes A> A.shouldEqual(other: A)
or whatever the syntax needs to be
p
Sam for MVP!
p
@sam maybe it's helpful if you posted your usecase in the youtrack