如何处理泛型函数的重载解析模糊性? [英] How to deal with an overload resolution ambiguity of functions with generics?

查看:582
本文介绍了如何处理泛型函数的重载解析模糊性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个类有两个函数,一个使用 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中定义),则一种可能的解决方法是执行



在几个类型参数冲突的情况下(例如<$当$ K f(key:K) f(value:V) c>和 V 都是 SomeType ),只需使用命名参数或将对象转换为 ban 其中一个函数(在Nothing 中)或让它接受任何


Consider this class with two functions, one with 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 = ...
}

When it is parameterized as C<Int, SomeType>, K is Int, and both functions match the calls, resulting into an error:

val m = C<Int, SomeType>()
m.f(1)

Overload resolution ambiguity. All these functions match:

  • public final fun f(index: Int): SomeType defined in C
  • public final fun f(key: Int): Pair<Int, SomeType>? defined in C

How do I call whichever f I want in this case?

解决方案

If you are lucky enough to have different parameter names of the functions, using named arguments will do the trick:

m.f(index = 1) // calls f(index: Int)
m.f(key = 1)   // calls f(key: K)

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 f(index: Int), you can use

    @Suppress("UNCHECKED_CAST")
    val s = (m as C<*, SomeType>).f(1) as Pair<Int, SomeType>
    

    The cast to 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>.

  • To call f(key: K), use:

    @Suppress("UNCHECKED_CAST")
    val s = (m as C<Any, SomeType>).f(1 as Any)
    

    Similarly, the cast to C<Any, SomeType> changes the signature of the desired function to f(key: Any), and to call it, just upcast 1 to Any.

It's all the same in case of several type parameters clashing (e.g. 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.

这篇关于如何处理泛型函数的重载解析模糊性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆