You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何指定满足继承android.view.View与实现MyInterface约束的抽象类型MyType?

解决方法:用Kotlin泛型约束实现双重类型要求

你的需求核心是要让foo方法的返回值同时满足「继承自View」和「实现MyInterface」两个约束,由于View是类而非接口,没法直接通过接口组合的方式定义一个新类型,这里最适合用Kotlin泛型的where子句来实现。

具体实现步骤

  1. 先定义你的自定义接口MyInterface:
interface MyInterface {
    fun myCustomFunction() // 你的自定义方法
}
  1. 定义OtherInterface时,给foo方法添加泛型约束:
interface OtherInterface {
    // 用where子句约束T必须同时是View的子类和MyInterface的实现类
    fun <T> foo(context: Context): T where T : View, T : MyInterface
}
  1. 实现OtherInterface和符合要求的具体类:
    比如你提到的MyImpl,它继承自LottieAnimationView(本身就是View的子类)并实现MyInterface:
class MyImpl(context: Context) : LottieAnimationView(context), MyInterface {
    override fun myCustomFunction() {
        // 这里实现你的自定义逻辑
    }
}

// 实现OtherInterface
class OtherInterfaceImpl : OtherInterface {
    override fun <T> foo(context: Context): T where T : View, T : MyInterface {
        // 返回MyImpl实例,通过as T完成类型转换(因为MyImpl符合T的约束)
        return MyImpl(context) as T
    }
}

使用效果

调用foo方法时,返回的对象无需额外强转,就能同时满足两种场景的需求:

val otherInterface = OtherInterfaceImpl()
val result = otherInterface.foo(context)

// 直接添加到FrameLayout(因为result是View的子类)
frameLayout.addView(result)
// 直接调用MyInterface的自定义方法(因为result实现了MyInterface)
result.myCustomFunction()

为什么不用typealias?

Kotlin的typealias只是给现有类型起别名,无法创建一个同时满足「类继承+接口实现」的抽象类型约束,所以泛型where子句是这个场景下的最优解。

内容的提问来源于stack exchange,提问作者jazzrc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 13:44:07