Kotlin:具有通用约束的委托
Kotlin: Delegation with generic constraints
我正在尝试找出声明 class 的语法,该委托还具有类型限制。例如,这是有效的语法:
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
class 并在派生的 class 上设置界限?
第一个版本是正确的,但你需要where
换行(可能是一个错误)
open class Cell<T>(val innerList: MutableList<T> = mutableListOf()) : MutableList<T> by innerList
where T : ClassFoo, T : InterfaceBar
我正在尝试找出声明 class 的语法,该委托还具有类型限制。例如,这是有效的语法:
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
class 并在派生的 class 上设置界限?
第一个版本是正确的,但你需要where
换行(可能是一个错误)
open class Cell<T>(val innerList: MutableList<T> = mutableListOf()) : MutableList<T> by innerList
where T : ClassFoo, T : InterfaceBar