首页 > 解决方案 > 如何细化返回类型的泛型参数?

问题描述

我需要的一个例子:

interface Interface1

sealed interface Interface2<P0: Interface1>

interface Interface3<P1: Interface1, P2: Interface2<out P1>> {
    // get error: Type parameter cannot have any other bounds if it's bounded by another type parameter
    fun <K: P1, G> getInterface2(): G where G: P2, G: Interface2<K> 
}

因此,在 Interface3 中,我需要返回 P2 和类 P1 的具体后代的函数。

我需要函数 getInterface2() 来获取具有 K 作为 P0 参数的 Interface2 的后代。

标签: kotlingenerics

解决方案


fun <G> getInterface2(): G where G: P2, G: Interface2<out P1>

应该具有相同的效果,因为 any Interface<K>extends Interface2<out P1>

旁注:我认为这是一个过度简化,但这个签名承诺返回 aG没有任何方法知道是什么G,所以它不能被合法地实现。


推荐阅读