如何处理泛型函数的重载解析模糊性? [英] How to deal with an overload resolution ambiguity of functions with generics?
问题描述
考虑这个类有两个函数,一个使用 Int
参数,另一个使用泛型:
class C< K,V> {
// ...
operator fun f(index:Int):Pair< K,V> = ...
operator fun f(key:K):V = ...
}
参数化为 C
时, K
为<$ c $
val m = C< Int,SomeType>()
mf(1)
重载分辨率模糊。所有这些函数匹配:
public final fun f(index:Int):SomeType
定义于C
public final fun f(key:Int):Pair< Int,SomeType>
C
$ b中定义的? $ b
在这种情况下,我如何调用任何 f
我想要的?
mf(index = 1) //调用f(index:Int)
mf(key = 1)//调用f(key:K)
否则,如果参数名称相同(或在Java中定义),则一种可能的解决方法是执行 调用 转换为 要调用 同样,转换为 在几个类型参数冲突的情况下(例如<$当$ Consider this class with two functions, one with When it is parameterized as
Overload resolution ambiguity. All these functions match: How do I call whichever If you are lucky enough to have different parameter names of the functions, using named arguments will do the trick: Otherwise, if the parameter names are the same (or defined in Java), one possible workaround is to perform unchecked casts to make the compiler choose the desired option: To call The cast to To call Similarly, the cast to It's all the same in case of several type parameters clashing (e.g. 这篇关于如何处理泛型函数的重载解析模糊性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
f(index:Int)
,您可以使用
@Suppress(UNCHECKED_CAST)$ (1)作为Pair< Int,SomeType> b> b val s =(m作为C< *,SomeType>)。
C< *,SomeType>
使 K
等同于在Nothing,out Any
中,这意味着 f(key:K)
没有有效的参数,所以这个调用自然被解析为 f(index:Int)
,但是你需要将结果转换回来,因为否则它是 Pair< Any, SomeType>
。
f(key:K)使用:
@Suppress(UNCHECKED_CAST)
val s =(m为C< Any,SomeType>) .f(1 as Any)
C< Any ,SomeType>
将所需函数的签名更改为 f(key:Any)
,并调用它,只需将 1
至任何
。
K $ c $时,c $ c> f(key:K)
和 f(value:V)
c>和 V
都是 SomeType
),只需使用命名参数或将对象转换为 ban 其中一个函数(在Nothing
中)或让它接受任何
。Int
argument, the other with a generic one:class C<K, V> {
// ...
operator fun f(index: Int): Pair<K, V> = ...
operator fun f(key: K): V = ...
}
C<Int, SomeType>
, K
is Int
, and both functions match the calls, resulting into an error:val m = C<Int, SomeType>()
m.f(1)
public final fun f(index: Int): SomeType
defined in C
public final fun f(key: Int): Pair<Int, SomeType>?
defined in C
f
I want in this case?m.f(index = 1) // calls f(index: Int)
m.f(key = 1) // calls f(key: K)
f(index: Int)
, you can use@Suppress("UNCHECKED_CAST")
val s = (m as C<*, SomeType>).f(1) as Pair<Int, SomeType>
C<*, SomeType>
makes K
equivalent to in Nothing, out Any
, meaning that there's no valid argument for f(key: K)
, so the call is naturally resolved to f(index: Int)
, but you need to cast the result back, because otherwise it is Pair<Any, SomeType>
.f(key: K)
, use:@Suppress("UNCHECKED_CAST")
val s = (m as C<Any, SomeType>).f(1 as Any)
C<Any, SomeType>
changes the signature of the desired function to f(key: Any)
, and to call it, just upcast 1
to Any
.f(key: K)
and f(value: V)
when K
and V
are both SomeType
), just use named arguments or cast the object to ban one of the functions (in Nothing
) or to make it accept Any
.