假设我有以下接口:
interface A
interface B
interface C
我想为A和B类型创建具有多个上限的类:
class First<T>(val t: T) where T : A, T : B
我也想对C类型使用委派:
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
通过查看类的语法,可以很快找出这两件事的顺序,您会看到委托说明符位于类型约束之前:
class
: modifiers ("class" | "interface") SimpleName
typeParameters?
primaryConstructor?
(":" annotations delegationSpecifier{","})?
typeConstraints
(classBody? | enumClassBody)
;
然后,只需要弄清楚如何按顺序执行这些工作即可-事实证明,如果将类型约束放在新行上,则可以正确解析这些内容(如此处和此处的文档所示):
class Third<T>(val t: T, val c: C) : C by c
where T : A, T : B
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句