templates - Kotlin:具有通用约束的委托(delegate)

标签 templates generics kotlin typename

我正在尝试找出声明具有委托(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/

相关文章:

wpf - 无法命令将切换按钮绑定(bind)为控件模板

c++ - Boost预处理器多个模板类生成

c++ - 如何反转可变参数模板函数的参数顺序?

java - Kotlin 继承与泛型

c# - 如何实例化通用类对象?

android - 如何将图标添加到内部存储文件夹,如Whatsapp或Snapchat(Android)

c++ - 为什么在使用模板和 stdarg 函数时 float 被提升为 double

java - Java泛型主要是一种在集合元素上强制静态类型的方法吗?

android - 如何在主线程上使用 Kotlin 协程 await()

android - 如何使用 View 绑定(bind)制作 BaseFragment