首页 > 解决方案 > Kotlin:具有通用约束的委托

问题描述

我试图找出语法来声明一个具有类型限制的委托类。例如,这是有效的语法:

open class Cell<T>(val innerList: MutableList<T> = mutableListOf()) : MutableList<T> by innerList

但现在我想强制执行TextendsClassFoo和 implements InterfaceBar。我把where关键字放在哪里?

以下是我尝试过的一些无法编译的事情:

open class Cell<T>(val innerList: MutableList<T> = mutableListOf()) : MutableList<T> by innerList where T : ClassFoo, T : InterfaceBar

open class Cell<T>(val innerList: MutableList<T> = mutableListOf()) where T : ClassFoo, T : InterfaceBar : MutableList<T> by innerList

open class Cell<T>(val innerList: MutableList<T> = mutableListOf()) : MutableList<T> where T : ClassFoo, T : InterfaceBar by innerList

这些限制与委派不兼容吗?换句话说,我应该只扩展我的Cell类并在派生类上设置界限吗?

标签: templatesgenericskotlintypename

解决方案


第一个版本是正确的,但你需要where换一个新行(可能是一个错误)

open class Cell<T>(val innerList: MutableList<T> = mutableListOf()) : MutableList<T> by innerList
        where T : ClassFoo, T : InterfaceBar

推荐阅读