Ole*_*han 5 generics delegation kotlin
假设我有以下接口:
interface A
interface B
interface C
Run Code Online (Sandbox Code Playgroud)
我想为类型 A 和 B 创建具有多个上限的类:
class First<T>(val t: T) where T : A, T : B
Run Code Online (Sandbox Code Playgroud)
我还想对 C 类型使用委托:
class Second(val c: C) : C by c
Run Code Online (Sandbox Code Playgroud)
我的问题是如何将两者结合在一个类声明中?
我试过这个:
class Third<T>(val t: T, val c: C) where T : A, T : B, C by c // syntax error: "Expecting : before the upper bound"
Run Code Online (Sandbox Code Playgroud)
和这个:
class Third<T>(val t: T, val c: C) : C by c where T : A, T : B // unresolved reference where
Run Code Online (Sandbox Code Playgroud)
通过查看类的语法,可以很快地弄清楚这两件事的顺序,您会看到委托说明符出现在类型约束之前:
class
: modifiers ("class" | "interface") SimpleName
typeParameters?
primaryConstructor?
(":" annotations delegationSpecifier{","})?
typeConstraints
(classBody? | enumClassBody)
;
Run Code Online (Sandbox Code Playgroud)
然后,只需弄清楚如何按该顺序进行这些工作即可 - 事实证明,如果将类型约束放在新行上,事情就会得到正确的解析(如此处和那里的文档所示):
class Third<T>(val t: T, val c: C) : C by c
where T : A, T : B
Run Code Online (Sandbox Code Playgroud)