我正在尝试找出声明具有委托(delegate)且也具有类型限制的类的语法。例如,这是有效的语法:
open class Cell<T>(val innerList: MutableList<T> = mutableListOf()) : MutableList<T> by innerList
但现在我想强制 T
扩展 ClassFoo
并实现 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
类并在派生类上放置边界吗?
最佳答案
第一个版本是正确的,但您需要将 where
放在新行上(可能是一个错误)
open class Cell<T>(val innerList: MutableList<T> = mutableListOf()) : MutableList<T> by innerList
where T : ClassFoo, T : InterfaceBar
关于templates - Kotlin:具有通用约束的委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60689208/