如何在 Kotlin 中将多个 Upper Bounds 语法与委托语法结合起来
How to combine multiple Upper Bounds syntax with delegation syntax in Kotlin
假设我有以下接口:
interface A
interface B
interface C
我想为类型 A 和 B 创建具有多个上限的 class:
class First<T>(val t: T) where T : A, T : B
我也想为类型 C 使用委托:
class Second(val c: C) : C by c
我的问题是如何将两者结合在一个 class 声明中?
我试过这个:
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 可以很快弄清楚这两件事的顺序,您会看到委托说明符出现在类型约束之前:
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
假设我有以下接口:
interface A
interface B
interface C
我想为类型 A 和 B 创建具有多个上限的 class:
class First<T>(val t: T) where T : A, T : B
我也想为类型 C 使用委托:
class Second(val c: C) : C by c
我的问题是如何将两者结合在一个 class 声明中?
我试过这个:
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 可以很快弄清楚这两件事的顺序,您会看到委托说明符出现在类型约束之前:
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