当函数声明一个类型参数时:
fun <T> typedFunction(value: T, option: Option<T>) { ... }
我该如何在kotlin中调用原始的un-typed typedFunction?
为什么?
在java我有:
// 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());
}
因为 typedFunction
声明了一个名为 T
的类型,并将其参数绑定到此声明的类型,并且在调用站点上我循环遍历多个值,这些值的确切类型未知(但已知是安全的,两个参数都符合相同类型)我可以不按照预期的方式调用typedFunction . 我必须将其转换为原始类型 .
如何在kotlin中实现相同的目标?
IntelliJ的功能:
这就是IntelliJ转换代码的方式:
val m: Map<Option<*>, *>? = ...
for ((key, value) in m!!) {
typedFunction<*>(key, value)
// ^^^ ERROR!!
}
但之后它会出现错误:“函数和属性的类型参数不允许进行预测”
1 回答
由于Kotlin没有原始类型,并且没有为函数调用提供星形投影等价物,因此
T
应该有一个具体的类型 .您可以将
Option<*>
参数的未经检查的强制转换为Option<Any>
,以便T
变为Any
: