假设我有以下接口(interface):
interface A
interface B
interface C
我想为类型 A 和 B 创建具有多个上限的类:
class First<T>(val t: T) where T : A, T : B
我还想对 C 类型使用委托(delegate):
class Second(val c: C) : C by c
我的问题是如何将两者结合在一个类声明中?
我尝试过这个:
class Third<T>(val t: T, val c: C) where T : A, T : B, C by c // syntax error: "Expecting : before the upper bound"
还有这个:
class Third<T>(val t: T, val c: C) : C by c where T : A, T : B // unresolved reference where
最佳答案
通过查看 grammar for classes 可以很快弄清楚这两件事的顺序。 ,您会看到委托(delegate)说明符位于类型约束之前:
class
: modifiers ("class" | "interface") SimpleName
typeParameters?
primaryConstructor?
(":" annotations delegationSpecifier{","})?
typeConstraints
(classBody? | enumClassBody)
;
然后,只需弄清楚如何使这些按顺序工作 - 事实证明,如果将类型约束放在新行上,事情就会得到正确的解析(如 documentation 中所示) :
class Third<T>(val t: T, val c: C) : C by c
where T : A, T : B
关于generics - 如何在 Kotlin 中将多个 Upper Bounds 语法与委托(delegate)语法结合起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51065694/