【问题标题】:Kotlin: Delegation with generic constraintsKotlin:具有通用约束的委托
【发布时间】:2020-03-15 12:40:43
【问题描述】:

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

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

但现在我想强制 T 扩展 ClassFoo 并实现 InterfaceBarwhere 关键字应该放在哪里?

以下是我尝试过的一些无法编译的东西:

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 类并在派生类上设置边界吗?

【问题讨论】:

    标签: templates generics kotlin typename


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-08
      • 1970-01-01
      • 2017-08-01
      • 2019-09-08
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多