Dougrinch
03/24/2020, 2:53 PMtypealias F<T> = (T) -> T
fun test() {
val id: F<*> = { it }
consume(id)//error here
}
fun <T> consume(v: F<T>) {
}
It looks like all should be fine, but the compiler tells me Type mismatch: inferred type is Any? but CapturedType(*) was expected
. I thought that the star means "some unknown T", am I wrong?streetsofboston
03/24/2020, 2:59 PMF<*>
is like (in Nothing) -> out Any?
Dougrinch
03/24/2020, 3:00 PMDougrinch
03/24/2020, 3:05 PMstreetsofboston
03/24/2020, 3:06 PMF
for any given type parameter that satisfies Function1<in Nothing, out Any?>
streetsofboston
03/24/2020, 3:07 PMT
that is a (sub)class of Nothing and a (super)class of Any?streetsofboston
03/24/2020, 3:09 PMconsume
function is declared in such a way that it cares about the type T
of F
, but you give it an instance that is declared to not care about its generic type. A function fun consume(v: F<*>)
will compile fine.Dougrinch
03/24/2020, 3:19 PMconsume
, I wouldn't do anything with v
except default Any
things (like toString
). Is this what you mean?streetsofboston
03/24/2020, 3:23 PMconsume
will actually never call invoke(..)
on v
, it will never call any other method that deals with T
, if F
had other such methods. Using v: F<*>
is therefore sufficient.Dougrinch
03/24/2020, 3:27 PMstreetsofboston
03/24/2020, 3:28 PMsize
or hashCode()
or isEmpty()
on a MutableList<*>
. None of these functions/properties use the generic parameter T
.
You can even call get(Int): T
on it and get an Any?
back safely, but it is kind-of meaningless.
You can_not_ call add(item: T)
on it (since there is no way of proving a value for item
, since it is of type `Nothing`…