Reputation: 1146
when a function declares a type parameter:
fun <T> typedFunction(value: T, option: Option<T>) { ... }
how should I call the raw un-typed typedFunction
in kotlin?
In java I have:
// This is a method in an external library. I can not change it.
void <T> typedFunction(T t, Option<T> o) { ... }
// This is my code. optionsValues contains many types
// such as Option<Integer>, Option<String>, and ...
Map<Option<?>, ?> m = readAndParseFromConfigFile();
for (Map.Entry<Option<?>, ?> e : m.entrySet()) {
// The cast does the trick!
// I know my code is safe, I can tell the compiler to back off.
typedFunction((Option) e.getKey(), e.getValue());
}
On the call site I'm looping over multiple values whose exact type is unknown (but known to be safe, both parameters conform to same type), hence I have to cast it into a raw type.
How can achieve the same in kotlin?
This is how IntelliJ converts my code:
val m: Map<Option<*>, *>? = ...
for ((key, value) in m!!) {
typedFunction<*>(key, value)
// ^^^ ERROR!!
}
But it gives an error afterwards: "Projections are not allowed on type arguments of functions and properties"
Upvotes: 3
Views: 1064
Reputation: 147951
Since Kotlin does not have raw types and does not provide a star-projection equivalent for function calls, there should be a concrete type for T
.
You can make an unchecked cast of the Option<*>
argument to Option<Any>
, so that T
becomes Any
:
val m: Map<Option<*>, *>? = ...
for ((key, value) in m!!) {
@Suppress("unchecked")
typedFunction(key as Option<Any>, value) // inferred T := Any
}
Upvotes: 2