```fun <T> T.foo(param: T) { } suspend fun...
# announcements
l
Copy code
fun <T> T.foo(param: T) {

}

suspend fun main() {
	val x = "text"
	val y = 42
	x.foo(y)
}
why does this code compile and run successfully even though x and y are of different types ?
s
first guess is that
T
is resolved to its default upper bound of
Any?
l
oh right thats problably it
is there any way i could enforce that the param completely matches the type the function extends ?
s
I mean, no, not really, not without enforcing a more concrete upper bound on one of your parameters
how do you plan on using a function like this?
actually it seems like on Kotlin/JVM, the generic gets resolved as an internal intersection type
{Comparable<*> & <http://java.io|java.io>.Serializable}
when using string and int lol
t
is there any way i could enforce that the param completely matches the type the function extends ?
The issue here is that type inference is very flexible. As long as there is some
T
that works for both parameters, the function can be used. It's also perfectly normal that you can call methods of a super class that your object's class inherits from. So the compiler doesn't know if you want to call
foo
on String or on Comparable, Serializable or whatever. In most cases that's exactly the behaviour you want from type inference. So without specifying some kind of bounds for
T
, you can't limit how far inference will go and the compiler will use the exact class of the receiver object for the type check. You could specify it explicitly of course (like
x.foo<String>(y)
) but I'm pretty sure that doesn't really help you.
💯 2
i
s there any way i could enforce that the param completely matches the type the function extends ?
@LastExceed We have a plan to provide some annotations that could alter flexibility of the type inference. In this example, they would limit
T
to be inferred either to the type of the receiver or the type of the parameter. Follow https://youtrack.jetbrains.com/issue/KT-13198 and https://youtrack.jetbrains.com/issue/KT-13138 for updates.
🆒 3