我可以从接口中的另一个泛型声明解析泛型类型吗? [英] Can I resolve a generic type from another generic declaration in an interface?

查看:70
本文介绍了我可以从接口中的另一个泛型声明解析泛型类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

期望您拥有这样的界面:

Expect you have an interface like this:

interface MyInterface<T : BaseClass<I>, I> {
    fun someMethod(param: I) : T
}

如您所见,我在 someMethod 中使用 I 作为参数.但是实际上当我实现这样的接口时,我不想声明 I :

As you can see I use I as a parameter in someMethod. But actually I don't want to declare I when I implement this interface like this:

class BaseClassImpl : BaseClass<OtherClass>

class Impl : MyInterface<BaseClassImpl, OtherClass> {
    override fun someMethod(param: OtherClass) {
        TODO("Not yet implemented")
    }
}

理论上,编译器可以解析 I 泛型而无需附加声明,因为它是由 BaseClassImpl 提供的.因此, MyInterface< BaseClassImpl> 应该已经提供了足够的信息来解决 someMethod()的必要泛型.

Theoretically it should be possible that the I generic can be resolved by the compiler without the additional declaration because it's provided by BaseClassImpl. So MyInterface<BaseClassImpl> should already provide enough information to resolve the necessary generic for someMethod().

在Kotlin中有什么方法可以实现这一目标吗?

Is there any way to achieve that in Kotlin?

推荐答案

在Kotlin中是不可能的.语言规范状态:

It's impossile in Kotlin. Language specification states:

Kotlin支持两种类型推断.

There are two kinds of type inference supported by Kotlin.

  • 本地类型推断,用于在语句/表达式范围内本地推断表达式的类型;
  • 函数签名类型推断,用于推断函数返回值和/或参数的类型.

它不能基于另一个泛型参数的类型来推断一个泛型参数的类型(尤其是对于超类型声明,因为它是构建类型约束系统的基础).

It can't infer type of one generic parameter based on the type of another (especially for supertype declaration, because it is a very base for building type constrains system).

您可以声明类型别名(针对每个 T ),以避免在每次实现此接口时重复 I :

You may declare typealiases (for each T) to avoid repating I each time you implement this interface:

typealias MyInterfaceForBaseClassImpl = MyInterface<BaseClassImpl, OtherClass>

class Impl : MyInterfaceForBaseClassImpl {
    override fun someMethod(param: OtherClass) : BaseClassImpl {
        //...
    }
}

这篇关于我可以从接口中的另一个泛型声明解析泛型类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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